每日一题(3) - 从尾到头打印链表

题目来自剑指Offer

题目

代码

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

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

void CreateList(LinkNode** pHead,int nLen)//头指针使用指针的指针
{
	assert(*pHead == NULL && nLen > 0);
	LinkNode* pCur = NULL;
	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;
			pCur = *pHead;
		}
		else
		{
			pCur->m_pNext = pNewNode;
			pCur = pNewNode;
		}
	}
}

void PrintList(LinkNode* pCurNode)
{
	if (NULL == pCurNode)
	{
		return;
	}
	else
	{
		PrintList(pCurNode->m_pNext);
		cout<<pCurNode->m_Data<<endl;
	}
}

int main()
{
	int nLen = 0;
	struct LinkNode* pHead = NULL;
	cout<<"please input node num: ";
	cin >> nLen;
	CreateList(&pHead,nLen);//注意传参使用引用
	PrintList(pHead);
	system("pause");
	return 1;
}


 

你可能感兴趣的:(每日一题(3) - 从尾到头打印链表)