【面试题】单链表反转-递归和非递归

#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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值