#include <stdio.h>
#include <stdlib.h>
typedef struct _Node
{
int data;
_Node* next;
}Node, *LinkList;
//一般反转
LinkList Reverse(LinkList &head)
{
if(head == NULL)
{
return NULL;
}
Node *pre, *cur, *next;
pre = head;
cur = head->next;
while(cur)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
head->next = NULL;
head = pre;
return head;
}
//递归反转
//注意最后返回值的next域置NULL
LinkList RReverse(LinkList p, LinkList &head)
{
if( (p==NULL) || (p->next==NULL) )
{
head = p;
return p;
}
else
{
LinkList tmp = RReverse(p->next, head);
tmp->next = p;
return p;
}
}
bool CreateList(LinkList &head, const int *data, const int len)
{
Node *cur = NULL;
Node *next = NULL;
int i;
cur = (LinkList)malloc(sizeof(Node));
if(cur == NULL)
{
return false;
}
cur->data = data[0];
cur->next = NULL;
head = cur;
for(i=1; i<len; i++)
{
next = (LinkList)malloc(sizeof(Node));
if(next == NULL)
{
return false;
}
next->data = data[i];
next->next = NULL;
cur->next = next;
cur = cur->next;
}
return true;
}
void PrintList(LinkList head)
{
while(head != NULL)
{
printf(" %d", head->data);
head = head->next;
}
}
void main( void )
{
int data[] = {1, 2, 3, 4, 5, 6};
int len = sizeof(data)/sizeof(int);
LinkList head;
if( !CreateList(head, data, len) )
{
printf("创建链表失败!\n");
return;
}
printf("反转前:");
PrintList(head);
printf("\n");
Reverse(head);
printf("反转后:");
PrintList(head);
printf("\n");
LinkList tail = RReverse(head, head);
tail->next = NULL;
//没有这条语句,则反转后的最后两个节点会形成环
printf("二次反转后:");
PrintList(head);
printf("\n");
}
【面试题】单链表反转-递归和非递归
最新推荐文章于 2024-09-16 11:30:43 发布