Skip to content

Latest commit

 

History

History
68 lines (60 loc) · 1.31 KB

从尾到头打印链表.md

File metadata and controls

68 lines (60 loc) · 1.31 KB

从尾到头打印链表

题目

输入一个链表,从尾到头打印链表每个节点的值。

思路 1

  • 利用堆栈实现

代码

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack stack = new Stack();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        ArrayList<Integer> result = new ArrayList<Integer>();
        while (!stack.isEmpty()) {
            result.add((Integer)stack.pop());
        }
        return result;
    }
}

思路 2

  • 递归实现
/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    ArrayList<Integer> result = new ArrayList<Integer>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
       if (listNode != null) {
           printListFromTailToHead(listNode.next);
           result.add(listNode.val);
       }
       return result;
    }
}