【九度OJ1518】|【劍指offer16】反轉鏈表

題目描述:

輸入一個鏈表,反轉鏈表後,輸出鏈表的全部元素。
(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);
			}
		}
	}

}
相關文章
相關標籤/搜索