3.从头到尾输出链表

从头到尾输出链表

题目描述

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

思路

1.反转链表
2.递归
3.栈

C++ 反转链表

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        ListNode* tail = NULL;
        while(head){
            ListNode *nex = head->next;
            head->next = tail;
            tail = head;
            head = nex;
        }
        vector<int> res;
        res.clear();
        while(tail){
            res.push_back(tail->val);
            tail = tail->next;
        }
        return res;
    }
};

C++ 递归

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> ret;
        if(!head)
            return ret;
        ret = printListFromTailToHead(head->next);
        ret.push_back(head->val);
        return ret;
    }
};

Java 反转链表

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode head) {
        ListNode tail = null;
        while(head != null){
            ListNode nex = head.next;
            head.next = tail;
            tail = head;
            head = nex;
        }
        ArrayList<Integer> lt = new ArrayList<Integer>();
        while(tail != null){
            lt.add(tail.val);
            tail = tail.next;
        }
        return lt;
    }
}

Java 递归

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode head) {
        ArrayList<Integer> lt = new ArrayList<Integer>();
        if(head == null)
            return lt;
        lt = printListFromTailToHead(head.next);
        lt.add(head.val);
        return lt;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33539027/article/details/107183821