题目见书《剑指offer》58页;
编程思路,链表数据用栈保存,利用栈先进后出的性质打印链表。
//面试题6:从尾到头打印链表
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
//单项链表的结点定义
struct ListNode
{
int m_nValue;
ListNode *m_pNext;
};
//用栈来实现
void PrintListReversingly_Iteratively(ListNode* pHead)
{
stack<ListNode*>nodes;
ListNode* pNode = pHead;
while (pNode != nullptr)
{
nodes.push(pNode); //用栈来保存链表数据
pNode = pNode->m_pNext;
}
while (!nodes.empty())
{
pNode = nodes.top();
cout << pNode->m_nValue << " ";
nodes.pop();//出栈
}
cout << endl;
}
//用递归来实现
void PrintListReversingly_Recursively(ListNode* pHead)
{
if (pHead != nullptr)
{
if (pHead->m_pNext != nullptr)
{
PrintListReversingly_Recursively(pHead->m_pNext);
}
/*printf("%d\t", pHead->m_nValue);*/
cout << pHead->m_nValue << " ";
}
}
int main()
{
ListNode* pHead = new ListNode();
ListNode *pNew, *pTemp;
pTemp = pHead;
int a[5] = { 5, 9, 6, 4, 3 };
for (int i = 0; i < 5; i++)
{
pNew = new ListNode;
pNew->m_nValue = a[i];
pNew->m_pNext = NULL;
pTemp->m_pNext = pNew;
pTemp = pNew;
}
//以上程序段是利用数组生成一个链表,生成的链表pHead为{0, 1, 4, 2, 5, 6},可以看出多了初始头结点0
ListNode *temp = pHead->m_pNext;//去掉初始头结点
cout << "利用栈方法从尾到头反过来打印链表的值如下:" << endl;
PrintListReversingly_Iteratively(temp);
cout << "利用递归方法从尾到头反过来打印链表的值如下:" << endl;
PrintListReversingly_Recursively(temp);
cout << endl;
system("pause");
return 0;
}
结果:
参考博客:
https://blog.csdn.net/qq_36427732/article/details/79900799
https://blog.csdn.net/qq_36631131/article/details/53543896