从尾到头打印链表(C++实现|测试用例)

代码:

#include<iostream>
#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;
  ListNode* pNode = pHead;
  while(pNode!=NULL)
  {
    nodes.push(pNode);
    pNode = pNode->m_pNext;
  }
  while(!nodes.empty())
  {
    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);
    }
    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;
}
posted @ 2020-10-06 09:41  诗和远方*  阅读(149)  评论(0编辑  收藏  举报