JAVA data structure Joseph problems learning 1.5

Joseph problems outlined

A bunch of people in a circle, starting from one number off, if the report five people out of this circle, leaving people count off again from the beginning, and asked who the last remaining;

Solution

A one-way circular linked list, in a while loop, prior to the remaining one (head.next = head), if encountered count == 5, the delete node, count starts again counting from 1, when the end of the cycle when the rest of the head is the last person

nitty gritty

When the node deletion circular list must be known before a node, the write cycle when the need to pay attention to ensure that every loop in while the current node and the previous node of the current node.

Code

package primDataStructure;

public class josephuQuestion {
	class cirNode{
		private String name;
		public cirNode next;
		public String getName() {
			return name;
		}
		public void deleteNext(cirNode preNode) {
			preNode.next=this.next;
		}
		public cirNode(String name) {
			this.next=this;
			this.name=name;
		}
		
	}
	public void solution() {
		cirNode head=new cirNode("同学0");
		for(int i=1;i<30;i++) {
			cirNode node=new cirNode("同学"+i);
			node.next=head.next;
			head.next=node;
		}
		int count=1;
		cirNode preNode=head;
		while(head.next!=head) {
			preNode=head;
			head=head.next;
			System.out.println(head.getName()+"叫号为"+count);
			
			if(count==5) {
				System.out.println(head.getName()+"叫到5,出列");
				count=1;
				head.deleteNext(preNode);
			}
			count++;
		}
		System.out.println("最后剩下了"+head.getName());
	}
	public static void main(String args[]) {
		josephuQuestion question=new josephuQuestion();
		question.solution();
	}
}

Published 13 original articles · won praise 1 · views 419

Guess you like

Origin blog.csdn.net/weixin_43458072/article/details/104331971