题目1511:从尾到头打印链表
发现如果用递归来做会通不过最后一组测试,所以还是用了Stack
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;
public class S5 {
public static void main(String[] args) throws FileNotFoundException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("S5.in"));
System.setIn(in);
Scanner cin = new Scanner(System.in);
ListNode head = null;
ListNode tail = null;
Stack<Integer> stack = new Stack<Integer>();
while (cin.hasNextInt()) {
int input = cin.nextInt();
if(input == -1){
break;
}
if(head == null){
head = new ListNode(input);
tail = head;
}else{
tail.next = new ListNode(input);
tail = tail.next;
}
stack.add(input);
}
// printout(head);
// reverseLinkedList(head);
reverseLinkedListStack(stack);
}
public static void reverseLinkedList(ListNode head){
if(head == null){
return;
}
reverseLinkedList(head.next);
System.out.println(head.val);
}
public static void reverseLinkedListStack(Stack stack){
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}
public static void printout(ListNode head){
while(head != null){
System.out.println(head.val);
head = head.next;
}
}
public static class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
next = null;
}
}
}