码迷,mamicode.com
首页 > 其他好文 > 详细

【剑指offer】递归循环两种方式反转链表

时间:2014-05-15 06:41:12      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:剑指offer   链表   反转链表   递归   非递归   

转载请注明出处:http://blog.csdn.net/ns_code/article/details/25737023


    本文分别用非递归和递归两种方式实现了链表的反转,在九度OJ上AC。

题目描述:

输入一个链表,反转链表后,输出链表的所有元素。
(hint : 请务必使用链表)

输入:

输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000):代表将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):代表链表元素。

输出:

对应每个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。

样例输入:
5
1 2 3 4 5
0
样例输出:
5 4 3 2 1
NULL
    很明显,翻转后,尾节点和头结点互换了。

    我们需要设置三个指针,分别指向当前要反转的节点、当前要反转节点的前一个节点、当前要反转节点的下一个节点。要注意链表为空,以及只有一个头结点的情况。

    非递归实现如下:

/*
反转链表,返回翻转后的头结点
*/
pNode ReverseList(pNode pHead)
{
	if(pHead == NULL)
		return NULL;
	if(pHead->next == NULL)
		return pHead;

	pNode pCur = pHead;
	pNode pPre = NULL;
	while(pCur != NULL)
	{
		pNode pNext = pCur->next;
		pCur->next = pPre;
		pPre = pCur;
		pCur = pNext;
	}
	return pPre;
}
    递归实现如下:

/*
递归实现反转链表,返回翻转后的头结点
*/
pNode ReverseListRecursivly(pNode pPre,pNode pCur)
{
	if(pCur == NULL)
		return NULL;
	if(pCur->next == NULL)
	{
		pCur->next = pPre;
		return pCur;
	}

	pNode pNext = pCur->next;
	pCur->next = pPre;
	pNode pNewHead = ReverseListRecursivly(pCur,pNext);
	return pNewHead;
}

pNode ReverseList2(pNode pHead)
{
	return ReverseListRecursivly(NULL,pHead);
}

    根据题目要求,测试代码如下:

int main()
{
	int n;
	while(scanf("%d",&n) != EOF)
	{
		pNode pHead = NULL;
		if(n > 0)
		{
			int i,data;
			scanf("%d",&data);
			pHead =(pNode)malloc(sizeof(Node));
			if(pHead == NULL)
				exit(EXIT_FAILURE);
			pHead->data = data;
			pHead->next = NULL;

			pNode pCur = pHead;
			for(i=0;i<n-1;i++)
			{
				scanf("%d",&data);
				pNode pNew =(pNode)malloc(sizeof(Node));
				if(pNew == NULL)
					exit(EXIT_FAILURE);
				pNew->data = data;
				pNew->next = NULL;
				pCur->next = pNew;
				pCur = pCur->next;
			}
		}

		pNode pNewHead = ReverseList2(pHead);
		if(pNewHead == NULL)
			printf("NULL\n");
		else
		{
			pNode pCur = pNewHead;
			while(pCur != NULL)
			{
				//这里主要时要注意输出的格式
				if(pCur->next == NULL)
					printf("%d\n",pCur->data);
				else
					printf("%d ",pCur->data);
				pCur = pCur->next;
			}
		}
	}
	return 0;
}

/**************************************************************
    Problem: 1518
    User: mmc_maodun
    Language: C
    Result: Accepted
    Time:150 ms
    Memory:2364 kb
****************************************************************/

【剑指offer】递归循环两种方式反转链表,布布扣,bubuko.com

【剑指offer】递归循环两种方式反转链表

标签:剑指offer   链表   反转链表   递归   非递归   

原文地址:http://blog.csdn.net/ns_code/article/details/25737023

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!