数据结构与算法 环形单链表(约瑟夫问题)

Java数据结构和算法
上一篇 主目录 下一篇

SingleCircleLinkedListDemo.java

package linkedlist;

import linkedlist.LinkedListNode;

public class SingleCircleLinkedListDemo {
     

	public static void main(String[] args) {
     
		// TODO Auto-generated method stub

		int[] people=new int[9];
		for(int i=0;i<9;i++) {
     
			people[i]=i+1;
		}
		int num=2;
		Josepful josepful=new Josepful(people,num);
		josepful.show();
		josepful.result();
	}

}


class SingleCircleLinkedList{
     
	public LinkedListNode head;
	SingleCircleLinkedList(){
     
		head=new LinkedListNode();
		head.next=head;
	}
	
	//环形链表的长度
	public int length() {
     
		LinkedListNode p=head;
		int length=0;
		while(p.next!=head) {
     
			p=p.next;
			length++;
		}
		return length;
	}
	
	//往单项环形节点添加数据
	public void  add(int val) {
     
		LinkedListNode p=head;
		while(p.next!=head) {
     
			p=p.next;
		}
		LinkedListNode l=new LinkedListNode(val);
		l.next=p.next;
		p.next=l;
		System.out.println("ok");
	}
	
	//删除数据
	public void del(int position) {
     
		LinkedListNode p=head;
		for(int i=0;i<position-1;i++) {
     
			p=p.next;
		}
		p.next=p.next.next;
		System.out.println("ok");
	}
	
	//显示环形链表数据
	public void show() {
     
		LinkedListNode p=head;
		System.out.println("List:");
		while(p.next!=head) {
     
			System.out.printf("%d\t",p.next.val);
			p=p.next;
		}
		System.out.println();
	}
}

class Josepful{
     
	public SingleCircleLinkedList scl;
	public int[] people;
	public int num;
	public Josepful(int[] people,int num) {
     
		this.people=people;
		this.num=num;
		scl=new SingleCircleLinkedList();
		create(people,scl);
	}
	
	//生成环
	public static void create(int[] people,SingleCircleLinkedList scl) {
     
		for(int i=0;i<people.length;i++) {
     
			scl.add(people[i]);
		}
	}
	//显示环
	public void show() {
     
		scl.show();
	}
	
	//输出
	public void result() {
     
		LinkedListNode head=scl.head;
		LinkedListNode p=head;
		int length=scl.length();
		while(length!=0) {
     
			for(int i=0;i<num-1;i++) {
     
				p=p.next;
			}
			if(p.next==head) {
     
				p.next=p.next.next;
			}
			System.out.printf("%d\t",p.next.val);
			length--;
			p.next=p.next.next;
		}
		System.out.println("ok");
	}
}

LinkedListNode.java

package linkedlist;

//链表结构,泛型类
class LinkedListNode{
     
	public int val;
	public LinkedListNode next;
	public LinkedListNode(int val) {
     
		this.val=val;
	}
	public LinkedListNode() {
     
		// TODO Auto-generated constructor stub
	}
}

你可能感兴趣的:(Java,数据结构,环形单链表,约瑟夫)