从尾到头打印链表

/*
* 输入一个链表的头节点,从尾到头反过来打印每个节点的值。
* 且不允许修改输入链表的结构。
*/

#include<iostream>
#include<stack>

using namespace std;

struct ListNode
{
	int m_nKey;
	ListNode* m_pNext;
};

/*
解法1:遍历整个链表,将遍历的元素进行压栈,然后再将栈中的数据输出,需要另外再申请O(n)的辅助空间
*/

void PrintListReversing_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();
	}
}

/*
* 解法2:递归的本质就是一个栈结构,可以利用递归来实现,每次访问一个节点的时候,
* 先递归输出它后面的节点,再输出该节点自身。有一个问题是当链表非常长的时候就会导致
* 函数导致函数调用的层级很深,从而有可能导致函数调用栈溢出。
*/

void PrintReversingly(ListNode* pHead)
{
	if (pHead != nullptr)
	{
		if (pHead->m_pNext != nullptr)
		{
			PrintReversingly(pHead->m_pNext);
		}

		cout << pHead->m_nKey << " ";
	}
}



int main()
{
	ListNode* node1 = new ListNode();
	ListNode* node2 = new ListNode();
	ListNode* node3 = new ListNode();
	ListNode* node4 = new ListNode();

	node1->m_nKey = 1;
	node2->m_nKey = 2;
	node3->m_nKey = 3;
	node4->m_nKey = 4;

	node1->m_pNext = node2;
	node2->m_pNext = node3;
	node3->m_pNext = node4;
	node4->m_pNext = nullptr;

	PrintListReversing_Iteratively(node1);
	cout << endl;

	PrintReversingly(node1);

	return 0;
}

  

posted on 2021-11-10 20:38  xcxfury001  阅读(19)  评论(0)    收藏  举报

导航