//链表的反转递归和非递归实现
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
//迭代法反转链表,
// p从指向第一个结点开始,当p存在,用s记录当前结点位置, 并让p后移记录下一个结点的位置,
//让当前结点的后继指针,指向其前驱结点,反转完成后head指向当前结点,表示当前结点为新的头
//由于反转链表后,第一个元素结点的后继指针,将变为NULL,所以在第一次反转前,让head为空
//在不停反转过程中,head始终指向当前完成反转的那个结点。直到最后一个结点反转完成,此时Head指向原链表的最后一个结点,该结点成为新的头
Node* reserveList1(Node* head)
{
Node *p = NULL, *s = NULL;
p = head;
head = NULL;
while (p) //当p存在
{
s = p; //s保存当前结点
p = p->next; //p保存下一个结点
s->next = head; //s指向其前驱
head = s; //s成为新的头
}
return head;
}
//递归法。
Node* reserveList2(Node *h)
{
if (h == NULL || h->next == NULL)
return h;
Node* NewHead = reserveList2(h->next);
h->next->next = h;
h->next = NULL;
return NewHead;
}
//循环打印链表
void printList(Node* head)
{
while (head != NULL)
{
printf("%d ", head->data);
head = head->next;
}
}
int main02()
{
//创建一个链表
Node s1, s2,s3,s4,s5;
s1.data = 1;
s2.data = 2;
s3.data = 3;
s4.data = 4;
s5.data = 5;
s1.next = &s2;
s2.next = &s3;
s3.next = &s4;
s4.next = &s5;
s5.next = NULL;
//打印原始链表
printList(&s1);
printf("*******************\n");
//打印迭代法反转后的链表
//printList(reserveList1(&s1));
printf("*******************\n");
//打印递归法反转后的链表
printList(reserveList2(&s1));
system("pause");
}