首页 > 技术文章 > 【剑指offer】从尾到头打印链表

Lrixin 2021-01-21 13:39 原文

题目链接:https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1

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


示例1
输入

{67,0,24,58}

返回值

[58,24,0,67]

解题思路:
(1)使用递归。
(2)使用栈。
(3)对于C++,可以使用使用reverse函数。


Cpp Code

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        //递归
        vector<int> ve;
        if(head==NULL){
            return ve;
        }
        else{
            ve=printListFromTailToHead(head->next);
            ve.push_back(head->val);
        }
        return ve;  
        //std::reverse()
        /*vector<int> ve;
        while(head!=NULL){
            ve.push_back(head->val);
            head=head->next;
        }
        reverse(ve.begin(), ve.end());
        return ve;*/
    }
};

Java Code

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        //使用栈
        ArrayList<Integer> al=new ArrayList<Integer>();
        Stack<Integer> st=new Stack<Integer>();
        while(listNode!=null){
            st.push(listNode.val);
            listNode=listNode.next;
        }
        while(!st.isEmpty()){
            al.add(st.pop());
        }
        return al;
        
        //递归
        /*ArrayList<Integer> al=new ArrayList<Integer>();
        if(listNode==null){
            return al;
        }
        else{
            al=printListFromTailToHead(listNode.next);
            al.add(listNode.val);
        }
        return al;*/
    }
}

推荐阅读