• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C语言反转单向链表

OC/C/C++ 水墨上仙 3026次浏览

反转单向链表分为递归和非递归两种方式。递归的实现方式比较简单,而非递归实现效率较高,在面试时应注意边界条件。
这道题在面试时被要求现场作答的概率还是很大的,比较tricky的地方就是要在当前条件下保存好next of next的指针,如果一时想不起来程序怎么写,可以先自己画个图看看。

// ReverseList.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
enum{N = 3};
class Node
{
public:
	Node* pNext;
	int var;
	Node(int i):pNext(NULL), var(i){}
};
void helper(Node* pHead, Node*& reverseHead)
{
	if(pHead->pNext->pNext != NULL)
		helper(pHead->pNext, reverseHead);
	else
		reverseHead = pHead->pNext;
	pHead->pNext->pNext = pHead;
}
Node* ReverseList(Node* pHead)
{
	if(NULL == pHead || NULL == pHead->pNext)
		return NULL;
	Node* reverseHead = NULL;
	helper(pHead, reverseHead);
	pHead->pNext = NULL;
	return reverseHead;
}
Node* ReverseListNonRecursive(Node* pHead)
{
	if(NULL == pHead || NULL == pHead->pNext)
	{
		return NULL;
	}
	Node* N1 = pHead->pNext;
	Node* N2 = pHead->pNext->pNext;
	
	if(NULL == N2)
	{
		N1->pNext = pHead;
		pHead->pNext = NULL;
	}
	else
	{
		Node* t = pHead;
		while (NULL != N2)
		{
			N1->pNext = pHead;
			pHead = N1;
			N1 = N2;
			N2 = N2->pNext;
		}
		N1->pNext = pHead;
		t->pNext = NULL;
	}
	return N1;
}
void PrintNode(Node* pHead)
{
	while (pHead != NULL)
	{
		printf("%d ",pHead->var);
		pHead = pHead->pNext;
	}
	printf("\r\n");
}
void Test()
{
	Node* pHead = new Node(0);
	Node* pNode = pHead;
	for(int i = 1; i < N; i++)
	{
		Node* pNext = new Node(i);
		pNode->pNext = pNext;
		pNode = pNode->pNext;
	}
	PrintNode(pHead);
	//Node* reversedHead = ReverseListNonRecursive(pHead);
	Node* reversedHead = ReverseList(pHead);
	PrintNode(reversedHead);
}
int _tmain(int argc, _TCHAR* argv[])
{
	Test();
	return 0;
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C语言反转单向链表
喜欢 (0)
加载中……