剑指offer 3、从头到尾打印链表 python和c++

题目:

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

思路:

把所有的链表节点值存到数组(列表,向量)里面,利用自带的反转函数反转输出。

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):
        l=[]
        while listNode:
            l.append(listNode.val)
            listNode = listNode.next
        l.reverse()
        return l
        #return l[::-1]
        # write code here

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> l;
        while (head != NULL){
            l.push_back(head->val);
            head = head->next;
        }
        reverse(l.begin(),l.end());
        return l;
    }
};
posted on 2021-06-10 17:18  雾恋过往  阅读(33)  评论(0编辑  收藏  举报

Live2D