题目:
输入一个链表的头结点, 从尾到头反过来打印出各结点的值
链表结点定义 typedef struct Node
{
int value;
struct Node *pNext;
}
思路:
遍历结点时,将结点值存放在栈中,再弹出栈打印
代码:
#include <iostream>
#include <stack>
using namespace std;
#define N 7
typedef struct Node
{
int value;
struct Node *pNext;
}Node;
void Insert(Node **pHead, int value)
{
Node *pNode = new Node;
pNode->value = value;
pNode->pNext = NULL;
if (*pHead == NULL)
{
*pHead = pNode;
return;
}
Node *pCur = *pHead;
while (pCur->pNext != NULL)
{
pCur = pCur->pNext;
}
pCur->pNext = pNode;
}
void ReversePrint(Node *pHead)
{
//在此填入代码
if (pHead == 0)
return;
stack<int> sta;
Node *pCur = pHead;
while (pCur)
{
sta.push(pCur->value);
pCur = pCur->pNext;
}
while (!sta.empty())
{
cout << sta.top() << " ";
sta.pop();
}
}
int main()
{
Node *pHead = NULL;
int a[N] = {1, 2, 3, 4, 5, 6, 7};
for (int i = 0; i < N; ++i)
{
Insert(&pHead, a[i]);
}
ReversePrint(pHead);
system("pause");
}