《剑指offer》—3、从尾到头打印链表

来源:互联网 发布:seo工作一年感想 编辑:程序博客网 时间:2024/06/10 02:45
题目描述
3、输入一个链表,从尾到头打印链表每个节点的值

解题思路:
方案1:遍历链表的每个节点,将该节点的数据存入vector,如果有下一个节点,则将其插入到vector的最前面(调用vector的insert函数),直至遍历完成。或者全部插入在后面,最后调用reverse函数翻转。
方案2:借助栈先进后出的特性,遍历后先全部入栈,再依次弹栈加入到vector数组中。
方案3:先将链表反转,再遍历存储在vector数组中。
另外也可采用从尾到头递归打印输出的方案实现,为熟悉链表操作,个人采用方案3实现编码。

参考代码:
/*************************************************Copyright:牛客网在线编程《剑指offer》Author:zhouyuanDate:2017-02-23Description:从尾到头打印链表**************************************************/#include <vector>using namespace std;struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}};class Solution {public:vector<int> printListFromTailToHead(ListNode* head) {ListNode *p, *q, *r;vector<int> array;if (head == NULL) {return array;}p = head;q = head->next;while (q != NULL) {r = q->next;q->next = p;p = q;q = r;}head->next = NULL;head = p;while (p != NULL){array.push_back(p->val);p = p->next;}return array;}};

1 0
原创粉丝点击