[原]《面试题精选》14.圆圈中最后剩下的数字

题目:n个数字(0,1,…,n-1)形成一个圆圈,从数字0开始,每次从这个圆圈中删除第m个数字(第一个为当前数字本身,第二个为当前数字的下一个数字)。当一个数字删除后,从被删除数字的下一个继续删除第m个数字。求出在这个圆圈中剩下的最后一个数字。


分析:这是一道约瑟夫环问题。思路就是按照提中的步骤去执行,很明显用到的数据结构是循环双向链表,关键是循环双链表的实现。见:Stacks,Queues,Linked Lists

public class LastNum{
	public static void main(String args[]){
		fun(7,2) ;
	}
	public static void fun(int n,int m){
		MyCircularLinkedList list = new MyCircularLinkedList() ;
		for(int i=0;i<n;i++){
			list.insert(i) ;
		}
		MyNode temp = list.first ;
		while(list.N!=1){
			for(int j=0;j<m-1;j++){
				temp = temp.next ;
			}
			list.del(temp) ;
			temp = temp.next ;
			
		}
		System.out.println(list.first.key) ;
	}
}

class MyCircularLinkedList{
	MyNode first ;
	MyNode last ;
	int N = 0 ;
	
	public void insert(int x){
		MyNode newNode = new MyNode(x) ;
		if(first == null){
			first = newNode ;
			last = newNode ;
			first.next = last ;
			last.next = first ;
			last.pre = first ;
			first.pre = last ;
			N++ ;
		}else{
			newNode.next = first ;
			first.pre = newNode ;
			last.next = newNode ;
			newNode.pre = last ;
	
			last = newNode ;
			N++ ;
		}
	}
	
	public void del(MyNode node){
		if(N==1){
			first = first ;
			last = last ;
		}
		if(N>1){
			if(node==first){
				first = node.next ;
			}
			if(node==last) last = node.pre ;
			
			node.pre.next = node.next ;
			node.next.pre = node.pre ;
		}
		N--;
	}
}
class MyNode{
	int key ;
	MyNode next ;
	MyNode pre ;
	
	public MyNode(int x){
		key = x ;
	}
}


作者:SpeedMe 发表于2014-4-16 20:20:28 原文链接
阅读:95 评论:0 查看评论

posted on 2014-04-16 20:20  狼牙灬月  阅读(242)  评论(0编辑  收藏  举报

导航