1. 程式人生 > >劍指offer--從尾到頭打印鏈表

劍指offer--從尾到頭打印鏈表

util sub nod next pub node 節點 arr mov

題目描述

輸入一個鏈表,從尾到頭打印鏈表每個節點的值。 1、利用棧,先入後出 import java.util.*;

class ListNode
{
int val;
ListNode next = null;

ListNode(int val)
{
this.val = val;
}
}

public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
LinkedList<Integer> stack = new LinkedList<Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
//入棧
ListNode point = listNode;
while(point != null){
stack.addFirst(point.val);
point = point.next;
}

//出棧
while(stack.size() > 0){
result.add(stack.removeFirst());
}

return result;
}
}

2、利用遞歸,非常巧妙

import java.util.*;

class ListNode
{
int val;
ListNode next = null;

ListNode(int val)
{
this.val = val;
}
}

public class Solution {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode)
{
/*
*遞歸
*/
if (listNode != null)
{
this.printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}

public static void main(String[] args)
{
ListNode listNode = new ListNode(2);
listNode.next = new ListNode(3);
listNode.next.next = new ListNode(4);
listNode.next.next.next = new ListNode(0);
Solution s = new Solution();
System.out.println(s.printListFromTailToHead(listNode));
}


}

劍指offer--從尾到頭打印鏈表