码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-05-21 09:44:40      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:java   笔试   算法   

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*/

找出单向链表中的倒数第k个结点,布布扣,bubuko.com

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

标签:java   笔试   算法   

原文地址:http://blog.csdn.net/dutsoft/article/details/26397745

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!