• 从尾到头打印链表(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<<' '<<' ';
    }
    //方法2递归调用实现
    void PrintListReversingly_Recursively(ListNode* pHead)
    {
      if(pHead != NULL)
      {
        if(pHead->m_pNext != NULL)
        {
          PrintListReversingly_Recursively(pHead->m_pNext);
        }
        std::cout << pHead->m_nKey << ' ';
      }
    }

    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;
    }
  • 相关阅读:
    Android中手机录屏并转换GIF的两种方式
    Android中访问sdcard路径的几种方式
    Android中开发工具Android Studio修改created用户(windows环境)
    [UOJ211][UER #6]逃跑
    [CF1168D]Anagram Paths
    [CF852H]Bob and stages
    Codechef BINOMSUM
    [ZJOI2019]开关
    [CF1161F]Zigzag Game
    [CF1149E]Election Promises
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13772709.html
Copyright © 2020-2023  润新知