【剑指offer】面试题 6:从尾到头打印链表

来源:互联网 发布:链表反转 递归java 编辑:程序博客网 时间:2024/05/17 23:06

题目描述

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

时间限制:1秒 空间限制:32768K 热度指数:243238
本题知识点: 链表

思路

第一种,从尾到头打印每一个节点的值,那么肯定要先遍历整个链表,再从尾部开始打印。这个过程是典型的“先入后出”,所以考虑用栈实现。遍历的时候,每遍历一个节点就放到栈中。遍历结束后,再从栈顶开始打印输出节点的值。

第二种,递归实现。反过来输出链表,则每访问一个节点的时候,先输出该节点后面的那个节点,再输出自身这个节点。递归之后,你会发现输出的就是反过来的链表了。

第三种,Python实现。先遍历链表,把每一个节点的值存放起来,之后输出的时候,直接反向输出即可。


参考代码

C++ 栈实现

/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    void printListFromTailToHead(ListNode* pHead) {        std::stack<ListNode*> nodes;                ListNode* pNode = pHead;        while (pNode != nullptr) {            nodes.push(pNode);            pNode = pNode->next;        }                while (!nodes.empty()) {            pNode = nodes.top();            printf("%d\t", pNode->val);            nodes.pop();        }    }};


C++ 递归实现

/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> printListFromTailToHead(ListNode* head) {        vector<int> value;        if (head != NULL) {            value.insert(value.begin(), head->val);            if (head->next != NULL) {                vector<int> tempVec = printListFromTailToHead(head->next);                if (tempVec.size() > 0)                    value.insert(value.begin(), tempVec.begin(), tempVec.end());            }        }        return value;    }};

Python 实现

# -*- coding:utf-8 -*-# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # 返回从尾部到头部的列表值序列,例如[1,2,3]    def printListFromTailToHead(self, listNode):        # write code here        result = []        if listNode is None:            return result        while listNode.next is not None:            result.extend([listNode.val])            listNode = listNode.next        result.extend([listNode.val])                return result[::-1]

总结

1、栈实现,应该是大家比较容易想到的方法,应该要掌握:

2、递归实现,虽然看着很棒的样子,但是有个缺陷,就是当链表的长度很大的时候,会导致调用的层级很深,导致函数调用栈溢出。

3、Python 实现,简单,但是资源占用很多,并不是最优的实现。



阅读全文
0 0
原创粉丝点击