从尾到头打印单链表 C++实现

从尾到头打印链表

题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
解法1:利用栈实现

废话不多说,直接上代码:

void Solution::printListRevers(ListNode *pHead)
{
	if(!pHead)
		return;
	std::stack<ListNode *> s_Nodes;

	ListNode *pNode = pHead->pNext;
	while(NULL != pNode)
	{
		s_Nodes.push(pNode);
		pNode = pNode->pNext;
	}
	while (!s_Nodes.empty())
	{
		printf("%d ", s_Nodes.top()->data);
		s_Nodes.pop();
	}
	return;
}
解法2:递归实现

需要注意,当链表非常长时,就会导致函数掉用的层级很深,有可能栈溢出;所以解法1较好。

void listNodeRecursion(ListNode *pHead)
{
	if(pHead)
	{
		listNodeRecursion(pHead->pNext);
		printf("%d ", pHead->data);
	}
	return;
}
void Solution::printListReversRecursion(ListNode *pHead)
{
	if(!pHead)
		return;
	ListNode *pTmpHead = pHead->pNext;
	listNodeRecursion(pTmpHead);
	return;
}
完整代码
#include "string.h"
#include "stdio.h"
#include <stack>
#include <iostream>

using namespace std;

struct ListNode
{
	int data;
	ListNode *pNext;
};

class Solution
{
public:
	Solution();
	~Solution();

	ListNode* InitList_head( int n);
	ListNode* InitList_Tail( int n);

	void printListRevers(ListNode *pHead);
	void printListReversRecursion(ListNode *pHead);
};
Solution::Solution()
{}
Solution::~Solution()
{
}

ListNode* Solution::InitList_head(int n)
{
	ListNode *pHead = (ListNode*)malloc(sizeof(ListNode));
	pHead->pNext = NULL;


	ListNode *pTmpHead = pHead;
	for(int i=0;i<n;i++)
	{
		ListNode *pNewNode = (ListNode*)malloc(sizeof(ListNode));
		pNewNode->data = i;

		pNewNode->pNext = pTmpHead->pNext;
		pTmpHead->pNext = pNewNode;

	}
	return pHead;
}

ListNode* Solution::InitList_Tail(int n)
{
	ListNode *pHead = (ListNode*)malloc(sizeof(ListNode));
	pHead->pNext = NULL;


	ListNode *pTmpTail = pHead;
	for(int i=0;i<n;i++)
	{
		ListNode *pNewNode = (ListNode*)malloc(sizeof(ListNode));
		pNewNode->data = i;

		pTmpTail->pNext = pNewNode;
		pNewNode->pNext = NULL;
		pTmpTail = pTmpTail->pNext;
	}
	return pHead;
}


void Solution::printListRevers(ListNode *pHead)
{
	if(!pHead)
		return;
	std::stack<ListNode *> s_Nodes;

	ListNode *pNode = pHead->pNext;
	while(NULL != pNode)
	{
		s_Nodes.push(pNode);
		pNode = pNode->pNext;
	}
	while (!s_Nodes.empty())
	{
		printf("%d ", s_Nodes.top()->data);
		s_Nodes.pop();
	}
	return;
}
void listNodeRecursion(ListNode *pHead)
{
	if(pHead)
	{
		listNodeRecursion(pHead->pNext);
		printf("%d ", pHead->data);
	}
	return;
}
void Solution::printListReversRecursion(ListNode *pHead)
{
	if(!pHead)
		return;
	ListNode *pTmpHead = pHead->pNext;
	listNodeRecursion(pTmpHead);
	return;
}

int main()
{
	Solution oTest;
	ListNode *pList = oTest.InitList_Tail(8);

	oTest.printListRevers(pList);
	printf("\n");
	oTest.printListReversRecursion(pList);
	std::cin.get();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值