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

来源:互联网 发布:全国人口数据库 编辑:程序博客网 时间:2024/06/14 18:52

题目描述

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

思路:

(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;}};



0 0