【九度OJ1517】|【劍指offer15】鏈表中倒數第k個結點

題目描述:

輸入一個鏈表,輸出該鏈表中倒數第k個結點。
(hint: 請務必使用鏈表。) java

輸入:

輸入可能包含多個測試樣例,輸入以EOF結束。
對於每一個測試案例,輸入的第一行爲兩個整數n和k(0<=n<=1000, 0<=k<=1000):n表明將要輸入的鏈表元素的個數,k表明要查詢倒數第幾個的元素。
輸入的第二行包括n個數t(1<=t<=1000000):表明鏈表中的元素。 node

輸出:

對應每一個測試案例,
如有結果,輸出相應的查找結果。不然,輸出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;
	}
}
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;
			st.nextToken();
			int num = (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(num > n)
				System.out.println("NULL");
			else{
				Node f = first;
				while(num > 1){
					f = f.next;
					num--;
				}
				System.out.println(f.data);
			}
		}
	}

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