用c++语言设计一算法,逆置带头结点的动态单链表L

要求用c++语言,带类模板
2024-11-20 13:40:17
推荐回答(1个)
回答1:

程序如下: #include
using namespace std;template
class Node
{
public:
T data;
Node *next;
Node()
{
next = NULL;
}
Node (T &x)
{
data = x;
next = NULL;
}
};template
class List
{
public:
List();
void create();
void reverse();
void print();private:
int count;
Node *head;
};template
List::List()
{
head = new Node();
head->next = NULL;
count = 0;
}template
void List::create()
{
T t;char ch = 'y';
Node *p = head;
cout << "输入链表中的值:" << endl;
while (ch == 'y')
{
cin >> t;
p->next = new Node(t);
p = p->next;
cout << "是否继续输(y/n)";
cin >> ch;
}
}template
void List::reverse()
{
Node *p = head->next, *oldnext = p->next, *pre = NULL;
while (p != NULL)
{
p->next = pre;
pre = p;
p = oldnext;
if (oldnext != NULL)
oldnext = oldnext->next;
}
head->next = pre;
}template
void List::print()
{
Node *p = head->next;
cout << "链表为:";
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}void main()
{
List l;
l.create();
l.print();
l.reverse();
l.print();
}