hw_机试_报数游戏(很有意思的一道题,解题思想:双向循环链表,尾插法)

 

很有意思的一道题,解题思想:双向循环链表,尾插法

 

题目描述

100个人围成一圈,每个人有一个编码,编号从1开始到100。他们从1开始依次报数,报到为M的人自动退出圈圈,然后下一个人接着从1开始报数,直到剩余的人数小于M。请问最后剩余的人在原先的编号为多少? 例如输入M=3时,输出为: “58,91” ,输入M=4时,输出为: “34,45,97”。
 

JAVA版代码

import java.util.Scanner;

public class Test4 {
	public static void main(String[] args) {
		Test4 test4 = new Test4();
		Node tmpHeader=test4.genedList(); 
		for (int i = 2; i <= 100; i++) {
			test4.insertList(tmpHeader, i);
		}

		Node itr = tmpHeader;
		do{
			System.out.print(itr.data+" ");
			itr=itr.rightNext;
		}while(itr != tmpHeader);
		System.out.println();
		System.out.print("m=");
		
		Scanner scan = new Scanner(System.in);
		int m = scan.nextInt();
		Node front=tmpHeader;
		while(test4.count(tmpHeader) >= m){
			for (int i = 1; i < m; i++) {
				tmpHeader=tmpHeader.rightNext;
			}
			tmpHeader.leftNext.rightNext = tmpHeader.rightNext;
			tmpHeader.rightNext.leftNext = tmpHeader.leftNext;
			tmpHeader = tmpHeader.rightNext;
		}
		
		Node itr1 = tmpHeader;
		while(itr1.data > itr1.leftNext.data){
			tmpHeader = itr1 = itr1.leftNext;  
		}
		do{
			System.out.print(itr1.data+" ");
			itr1=itr1.rightNext;
		}while(itr1 != tmpHeader);
	}
		
	private int count(Node top){
		Node p=top;
		int total=0;
		do{
			++total;
		}while((p=p.rightNext) != top);
		return total;
	}
	
	private Node genedList(){
		Node top=new Node(1);
		top.leftNext = null;
		top.rightNext = null;
		return top;
	}
	
	private boolean insertList(Node tmpHeader,int ele){
		Node p=tmpHeader;
		Node q=tmpHeader; 
		while(p.rightNext !=q && p.rightNext != null){
			p=p.rightNext;
		}
		Node newP=new Node(ele);
		newP.data=ele;
		p.rightNext = newP;
		newP.leftNext = p;
		q.leftNext = newP;
		newP.rightNext = q;
		return true;
	}
	
	private class Node{
		private Node leftNext;  
		private Node rightNext; 
		private int data;  
		public Node(int data){
			this.data=data;
		}
	}
}

 

你可能感兴趣的:(hw_机试_报数游戏(很有意思的一道题,解题思想:双向循环链表,尾插法))