找出单向链表中的倒数第k个结点

2014-11-23 20:19:23 · 作者: · 浏览: 13
import java.util.Scanner;

public class List {
	private Node first;
	private int N;
	class Node{
		int data;
		Node next;
	}
	//顺便复习一下链表
	public int size() { return N; }
	public boolean isEmpty() { return first==null; }
	
	public Node FindPrev(int pos){
		Node tmp=first;
		for(int i=1;i<=pos-1;i++)
			tmp=tmp.next;
		return tmp;
	}
	public boolean insert(int n,int pos){
		if(pos>n || pos<=0){
			System.out.println("illegal insert postion");
			return false;
		}
		Node tmp;
		tmp=FindPrev(pos);
		
		Node node=new Node();
		node.data=n;
		node.next=tmp.next;
		tmp.next=node;
		
		N++;
		return true;
	}
	//链表直接当栈使用
	public void push(int n){
		Node oldfirst=first;
		first=new Node();
		first.data=n;
		first.next=oldfirst;
		N++;
	}
	
	public int GetInverseKth(int k){
		Node p=first;
		Node q=first;
		while((k--)>
0){ p=p.next; } while(p!=null){ p=p.next; q=q.next; } return q.data; } public void print(){ Node tmp=first; while(tmp!=null){ System.out.print(tmp.data+" "); tmp=tmp.next; } System.out.println(); } public static void main(String[] args) { List l=new List(); for(int i=1;i<=10;i++){ l.push(i); } l.print(); int k; System.out.println("请输入k:"); Scanner cin=new Scanner(System.in); k=cin.nextInt(); int val=l.GetInverseKth(k); System.out.println("倒数第 "+k+" 个结点的值为:"+val); } } /* test output 10 9 8 7 6 5 4 3 2 1 请输入k: 7 倒数第 7 个结点的值为:7*/