输入一个链表,反转链表后,输出链表的全部元素。
(hint : 请务必使用链表) java
输入可能包含多个测试样例,输入以EOF结束。
对于每一个测试案例,输入的第一行为一个整数n(0<=n<=1000):表明将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):表明链表元素。 node
对应每一个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。 测试
5 1 2 3 4 5 0样例输出:
5 4 3 2 1 NULL
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; class Node{ public int data; public Node next; public Node(int data){ this.data = data; } } /** * 反转链表 * @author aqia358 * */ public class Main { public static void main(String[] args) throws IOException { StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); while(st.nextToken() != st.TT_EOF){ int n = (int) st.nval; Node first = new Node(-1); int count = 0; while(count < n){ st.nextToken(); int t = (int) st.nval; Node node = new Node(t); node.next = first; first = node; count++; } if(n <= 0) System.out.println("NULL"); else{ Node f = first; while(f.next.data != -1){ System.out.print(f.data+" "); f = f.next; } System.out.println(f.data); } } } }