从尾到头打印链表(C++实现|测试用例)
代码:
#include<iostream>
#include<stack>
#include<stack>
using namespace std;
class ListNode{
public:
int m_nKey;
ListNode* m_pNext;
ListNode(int data):m_pNext(nullptr){
this->m_nKey = data;
}
} ;
//方法1栈结构实现;
void PrintListReversingly_Iteratively(ListNode* pHead)
{
std::stack<ListNode*> nodes;
public:
int m_nKey;
ListNode* m_pNext;
ListNode(int data):m_pNext(nullptr){
this->m_nKey = data;
}
} ;
//方法1栈结构实现;
void PrintListReversingly_Iteratively(ListNode* pHead)
{
std::stack<ListNode*> nodes;
ListNode* pNode = pHead;
while(pNode!=NULL)
{
nodes.push(pNode);
pNode = pNode->m_pNext;
}
{
nodes.push(pNode);
pNode = pNode->m_pNext;
}
while(!nodes.empty())
{
pNode = nodes.top();
std::cout <<pNode->m_nKey << ' ';
nodes.pop();
}
cout<<'\n'<<'\n';
{
pNode = nodes.top();
std::cout <<pNode->m_nKey << ' ';
nodes.pop();
}
cout<<'\n'<<'\n';
}
//方法2递归调用实现
void PrintListReversingly_Recursively(ListNode* pHead)
{
if(pHead != NULL)
{
if(pHead->m_pNext != NULL)
{
PrintListReversingly_Recursively(pHead->m_pNext);
}
{
if(pHead != NULL)
{
if(pHead->m_pNext != NULL)
{
PrintListReversingly_Recursively(pHead->m_pNext);
}
std::cout << pHead->m_nKey << '\n';
}
}
}
}
int main()
{
ListNode* a = new ListNode(1);
ListNode* b = new ListNode(2);
ListNode* c = new ListNode(3);
ListNode* d = new ListNode(4);
ListNode* e = new ListNode(5);
a->m_pNext = b;
b->m_pNext = c;
c->m_pNext = d;
d->m_pNext = e;
e->m_pNext = nullptr;
ListNode* pHead = a;
PrintListReversingly_Iteratively(a);
PrintListReversingly_Recursively(pHead);
return 0;
}
b->m_pNext = c;
c->m_pNext = d;
d->m_pNext = e;
e->m_pNext = nullptr;
ListNode* pHead = a;
PrintListReversingly_Iteratively(a);
PrintListReversingly_Recursively(pHead);
return 0;
}