剑指offer第五题,链表节点先入后出,想到用栈实现,代码如下
package com.zjy.sword2offer;
import java.util.Stack;
class ListNode{
int val;
ListNode next;
ListNode(int value){
val = value;
}
}
public class PrintListReversely {
public static void printListReversely(ListNode head){
if(head==null)
return;
Stack<ListNode> sta = new Stack<ListNode>();
ListNode current = head;
while(current!=null)
{
sta.push(current);
if(current.next!=null)
current = current.next;
else
break;
}
while(!sta.isEmpty())
{
ListNode tmp = sta.peek();
sta.pop();
System.out.println(tmp.val);
}
}
}
当然用栈实现想到了递归,代码很简洁,但是效率较低
package com.zjy.sword2offer;
public class PrintListReversely_Recursively {
public static void PrintRecursively(ListNode head){
if(head==null)
return;
if(head.next!=null)
{
PrintRecursively(head.next);
}
System.out.println(head.val);
}
}