首页 > 代码库 > 剑指offer--从尾到头打印链表

剑指offer--从尾到头打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值。
 
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--从尾到头打印链表