c语言程序设计习题之从尾到头打印链表



c语言程序设计习题之从尾到头打印链表。c++链表应用实例。

题目来自剑指Offer

c++算法题目:输入一个链表的头结点,从头到尾反过来打印出每个结点的值。

c++练习代码实例:

#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;
}