从尾到头打印链表

题目描述

输入链表的第一个节点,从尾到头反过来打印出每个结点的值。

解题思路
  1. 新建简单的链表用以测试
  2. 会遍历正确顺序的链表数据
  3. 不同的方法实现:
    1. 利用栈
      #include <iostream>
      #include <vector>
      #include <stack>
      #include <string>
      using namespace std;
      
      //带头节点的链表
      typedef struct ListNode
      {
      	int m_element;
      	ListNode* m_pNextNode;
      } *List, *Node;
      
      
      bool isFind(List L, int num)
      {
      	List pList = L->m_pNextNode;
      	while (pList != nullptr)
      	{
      		if (pList->m_element == num)
      			return true;
      		pList = pList->m_pNextNode;
      	}
      	return false;
      }
      
      List CreatList()
      {
      	ListNode *pHead = new ListNode;
      	pHead->m_element = -999;
      	pHead->m_pNextNode = nullptr;
      	List pCurPreList = pHead;//待插入节点的前一节点
      	int num;
      	cout << "Input data(-999 to quit) to creat list:" << endl;
      	while (1)
      	{
      		cin >> num;
      		if(num == -999)
      			break;
      		else
      		{
      			if (!isFind(pHead, num))
      			{
      				Node newNode = new ListNode;
      				newNode->m_pNextNode = nullptr;
      				newNode->m_element = num;
      				pCurPreList->m_pNextNode = newNode;
      				pCurPreList = newNode;//更新
      			}
      		}
      	}
      	return pHead;
      }
      
      class Solution {
      public:
      	vector<int> printListFromTailToHead(ListNode* head)
      	{
      		stack<int> st;
      		vector<int> out;
      		List pList = head->m_pNextNode;
      		while (pList != nullptr)
      		{
      			st.push(pList->m_element);
      			pList = pList->m_pNextNode;
      		}
      		while (!st.empty())
      		{
      			out.push_back(st.top());
      			st.pop();
      		}
      		return out;
      	}
      };
      
      int main()
      {
      	Solution sol;
      	List L = CreatList();
      	vector<int> reverse;
      	reverse = sol.printListFromTailToHead(L);
      	for (int i = 0; i < reverse.size(); i++)
      	{
      		cout << reverse[i] << " ";
      	}
      	cout << endl;
      	system("pause");
      	return 0;
      }
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值