剑指offer(C++)——从尾到头打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值。

思路:

(1)由于链表只能从头到尾进行遍历,于是我们就想如果能把链表的指针翻转过来,我们就可以实现从尾到头的输出了。但是这里有个问题,就是我们这样做会改变原始链表的结构。如果没有要求说不能改变链表的结构,那么我们就可以采用头插法来实现翻转链表。

(2)如果要求不能改变原始链表结构怎么办呢?在遍历链表的时候,我们可以借用一个栈来保存遍历到的结点值,然后在一个一个弹出栈,实现链表从尾到头的打印。同时,由于递归在本质就是一个栈结构,所以也可以用递归来实现,在打印一个结点的时候,递归打印它的下一个结点,然后在打印该结点。

实现的代码如下:

/*链表数据结构*/
struct ListNode {
	int val;
    struct ListNode *next;
	ListNode(int x) :
		val(x), next(NULL) {}
};
/*基于栈的方法实现*/
class Solution {
public:
	vector<int> printListFromTailToHead(ListNode* head) {
		stack<int> nodes;
		vector<int> Value;
		ListNode* pNode = head;
		while (pNode != NULL)
		{
			nodes.push(pNode->val);
			pNode = pNode->next;
		}
		while (!nodes.empty())
		{
			Value.push_back(nodes.top());
			nodes.pop();
		}
		return Value;
	}
};
/*递归方法实现*/
class Solution {
public:
	void print(ListNode* head, vector<int>& Val)
	{
		if (head != NULL)
		{
			print(head->next, Val);
			Val.push_back(head->val);
		}
	}
	vector<int> printListFromTailToHead(ListNode* head) {
		vector<int> Value;
		if (head != NULL)
			print(head, Value);
		return Value;
	}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值