下面是PrintListInReversedOrder.h文件,利用两种方法
// 面试题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 << " ";
}
}
下面是PrintListInReversedOrder.cpp文件,包含主函数
#include<iostream>
#include<list>
#include"PrintListInReversedOrder.h"
using namespace std;
int main()
{
ListNode* pHead = new ListNode();
ListNode *pNew, *pTemp;
pTemp = pHead;
int a[5] = { 1, 4, 2, 5, 6 };
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;
return 0;
}
测试结果如下:
利用栈方法从尾到头反过来打印链表的值如下:
6 5 2 4 1
利用递归方法从尾到头反过来打印链表的值如下:
6 5 2 4 1
请按任意键继续. . .