从头到尾打印链表
程序员文章站
2022-06-05 19:42:29
...
//6_从尾到头打印链表
/*c++ stl栈stack的头文件为:
#include <stack>
c++ stl栈stack的成员函数介绍
操作 比较和分配堆栈
empty() 堆栈为空则返回真
pop() 移除栈顶元素
push() 在栈顶增加元素
size() 返回栈中元素数目
top() 返回栈顶元素*/
#include<iostream>
#include<stack>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode *m_pNext;
};
ListNode * CreateListNode(int vaule);
void ConnectListNodes(ListNode *pHead, ListNode *pLast);
void destroyNode(ListNode *pHead);
void PrintListReverse_Iteratively(ListNode *pHead);
void PrintListReverse_Recursively(ListNode *pHead);
int main()
{
ListNode* pNode1 = CreateListNode(1);
ListNode* pNode2 = CreateListNode(2);
ListNode* pNode3 = CreateListNode(3);
ListNode* pNode4 = CreateListNode(4);
ListNode* pNode5 = CreateListNode(5);
ConnectListNodes(pNode1, pNode2);
ConnectListNodes(pNode2, pNode3);
ConnectListNodes(pNode3, pNode4);
ConnectListNodes(pNode4, pNode5);
PrintListReverse_Iteratively(pNode1);
cout << endl;
PrintListReverse_Recursively(pNode1);
destroyNode(pNode1);
cin.get();
return 0;
}
ListNode * CreateListNode(int vaule)
{
ListNode *p_node = new ListNode();
p_node->m_nKey = vaule;
p_node->m_pNext = nullptr;
return p_node;
}
void ConnectListNodes(ListNode *pHead, ListNode *pLast)
{
if (pHead == nullptr)
{
cout << "Error to connect two nodes.\n";
exit(1);
}
pHead->m_pNext = pLast;
}
void destroyNode(ListNode *pHead)
{
ListNode* pNode = pHead;
while (pNode != nullptr)
{
pHead = pHead->m_pNext;
delete pNode;
pNode = pHead;
}
}
void PrintListReverse_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_nKey << ' ';
nodes.pop();
}
}
void PrintListReverse_Recursively(ListNode *pHead)
{
if (pHead!=nullptr)
{
if (pHead->m_pNext != nullptr)
{
PrintListReverse_Iteratively(pHead->m_pNext);
}
cout << pHead->m_nKey;
}
}