节点的定义:
typedef struct Node
{
int data;
Node *next;
}Node;
创建链表:
Node *CreatList()
{
Node *node1,*node2,*head;//*head用来标记链表,node1总是用来指向新分配的内存空间,
//node2总是指向尾结点,并通过node2来链入新分配的结点*/
head = nullptr;
int dataa;
while(1)
{
cout<<"请输入链表的整形数(输入-1表示空链表):";
cin>>dataa;
if (dataa == -1)
break;
else
{
node1 = new Node;
node1->data = dataa;
node1->next = nullptr;
if(head==nullptr)
{
head = node1;
node2 = node1;
}
else
{
node2->next = node1;
node2 = node1;
}
}
}
cout<<"链表创建成功!\n";
return head;
}
递归实现链表的翻转:
Node* reverseList2(Node* head)
{
if(head == NULL || head->next == NULL)
return head;
Node* newHead = reverseList2(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
非递归实现链表的翻转:
Node *ReverseList(Node *head)
{
if(head == nullptr || head->next == nullptr)
return head;
Node *p,*q,*r;
p = head;
q = head->next;
while(q)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head->next=nullptr;
head = p;
return head;
}