剑指offer | 从尾到头打印链表 | 11

思路分析

从尾到头打印链表没有一个好的思路,就是先从头到尾遍历一次链表,依次加入一个列表,最后再对这个列表进行逆序操作.

cpp

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        ListNode* p = head;
        vector<int> arr;
        while(p){
            arr.push_back(p->val);
            p=p->next;
        }
        reverse(arr.begin(),arr.end());
        return arr;
    }
};

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):
        arr = []
        p = listNode
        while p:
            arr.append(p.val)
            p = p.next
        return arr[::-1]
原文地址:https://www.cnblogs.com/Rowry/p/14305349.html