每日一题(4) - 反转链表

题目来自剑指Offer

题目

每日一题(4) - 反转链表_第1张图片

代码

#include <iostream>
#include <assert.h>
using namespace std;

struct LinkNode 
{
	int m_Data;
	struct LinkNode* m_pNext;
};

void ReverseList(LinkNode* pHead)
{
	assert(pHead != NULL);
	LinkNode* pCurNode = NULL;
	LinkNode* pNextNode = NULL;
	pCurNode = pHead->m_pNext;
	pHead->m_pNext = NULL;
	while (pCurNode)
	{
		pNextNode = pCurNode->m_pNext;

		pCurNode->m_pNext = pHead;
		pHead = pCurNode;

		pCurNode = pNextNode;
	}
	return pHead;
}

void CreateListBackword(LinkNode*& pHead,int nLen)
{
	assert(pHead == NULL && nLen > 0);
	LinkNode* pNewNode = NULL;
	for (int i = 0;i < nLen;i++)
	{
		pNewNode = new LinkNode;
		cin>>pNewNode->m_Data;
		pNewNode->m_pNext = NULL;

		if (pHead == NULL)
		{
			pHead = pNewNode;
		}
		else
		{
			pNewNode->m_pNext = pHead;
			pHead = pNewNode;
		}
	}
}


void PrintList(LinkNode* pHead)
{
	assert(pHead != NULL);
	while (pHead)
	{
		cout<<pHead->m_Data<<" ";
		pHead = pHead->m_pNext;
	}
	cout<<endl;
}

int main()
{
	int nLen = 0;
	struct LinkNode* pHead = NULL;
	cout<<"please input node num: ";
	cin >> nLen;
	CreateListBackword(pHead,nLen);
	PrintList(pHead);
	pHead = ReverseList(pHead);
	PrintList(pHead);
	system("pause");
	return 1;
}


 

 

你可能感兴趣的:(每日一题(4) - 反转链表)