剑指offer----链表(一):从尾到头打印链表

题目描述:输入一个链表,从尾到头打印链表每个节点的值。

思路:假设不修改原链表的结构。返回一个反序的链表,这就是典型的“后进先出”,我们可以用栈实现这种顺序。每经过一个结点的时候,把该结点放到一个栈中。当遍历完整个链表后,再从栈顶开始逐个输出结点的值,给一个新的链表结构,这样链表就实现了反转。

代码:

Python版

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        result = []
        while listNode:
            result.insert(0,listNode.val)
            listNode = listNode.next
        return result

C/C++版:

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> stack;
        vector<int> result;
        struct ListNode *p = head;
        if(head != NULL) 
        {
            stack.push(p->val);
            while((p=p->next) != NULL)
            {
                stack.push(p->val);
            }
            while(!stack.empty())
            {
                result.push_back(stack.top());
                stack.pop();
            }
        }
        return result;
    }
};

知识点补充:

Python List insert()方法:

insert() 函数用于将指定对象插入列表的指定位置。

list.insert(index, obj)
  • index -- 对象 obj 需要插入的索引位置。
  • obj -- 要插入列表中的对象。


猜你喜欢

转载自blog.csdn.net/zhourunan123/article/details/80173019
今日推荐