欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

链表逆序

程序员文章站 2024-03-05 23:22:37
...
#include <iostream>
using namespace std;

struct Node
{
	int nData;
	Node * pNext;
};

Node *CreateList(Node* pHead)
{
	Node * pTemp;
	for(int i = 1;i<10;i++)
	{
		pTemp = new Node();
		pTemp->nData = i;
		pTemp->pNext = pHead;
		pHead = pTemp;
	}
	return pHead;
}

Node *ReverseList(Node* pHead)
{
	Node* p1 = pHead;
	Node* p2 = NULL;
	while(p1)
	{
		Node * pTemp = p1->pNext;
		p1->pNext = p2;
		p2 = p1;	
		p1 = pTemp;		
	}
	return p2;
}

void ReverseList(Node** pHead)
{
	Node* p1 = *pHead;
	Node* p2 = NULL;
	while(p1)
	{
		Node * pTemp = p1->pNext;
		p1->pNext = p2;
		p2 = p1;	
		p1 = pTemp;		
	}
	*pHead = p2;
}

Node * ReverseList_Digui(Node* pHead,Node* pHead2 = NULL)
{
	if(pHead == NULL)
		return pHead2;
	Node * pTemp = pHead->pNext;
	pHead->pNext = pHead2;	
	return ReverseList_Digui(pTemp,pHead);
}

void Printf(Node* pHead)
{
	Node * pTemp = pHead;
	while(pTemp)
	{
		cout<<pTemp->nData<<",";
		pTemp = pTemp->pNext;
	}
	cout<<endl;
}

int main()
{
	Node * pHead;
	pHead = new Node();
	pHead->nData = 0;
	pHead->pNext=NULL;
	pHead = CreateList(pHead);
	Printf(pHead);

	pHead = ReverseList(pHead);
	Printf(pHead);

	ReverseList(&pHead);
	Printf(pHead);

	pHead = ReverseList_Digui(pHead);
	Printf(pHead);
	getchar();
}


 

转载于:https://www.cnblogs.com/byfei/archive/2012/06/27/3112405.html

上一篇: 数组工具类Arrays

下一篇: 2021-01-11