Josephu问题-上——创建环形链表

import java.util.Scanner;
class Person{
	int no;
	Person nextPerson = null;
	public Person(int no){
		this.no = no;
	}
}
class CycleLink{
	Person firstPerson = null; //指向链表第一个小孩的引用
	int len; 
	Person temp = null;
			//设定链表长度
	public void setLen(int len){
		this.len = len;
	}
			//创建链表
	public void createLink(){
		for(int i=1; i<=len; i++){
			Person p = new Person(i);
				//环链的第一个对象
			if(i==1){
				this.firstPerson = p;	//将第一个对象的引用存放在firstPerson中
				this.temp = p;	//将第一个对象的引用暂时赋于temp,用于接收下一个对象的引用
			}
				//环链的最后一个对象
			else if(i==len){
				this.temp.nextPerson = p;	//将最后一个对象的引用赋给倒数第二个对象的nextPerson
				temp = p;		//将当前对象(也就是最后一个对象)的引用暂赋给temp
				temp.nextPerson = this.firstPerson;	//将第一个对象的引用赋给最后一个对象的nextPerson
				
			}else{
				this.temp.nextPerson = p;//将当前对象的引用赋给上一个对象的引用变量nextPerson中
				this.temp = p;	//将当前对象的引用暂时赋于temp,用于接收下一个对象的引用
			}
		}
	}
			//打印环形链表
	public void showLink(){
		Person t = firstPerson;	
		do{
			System.out.println(t.no);
			t = t.nextPerson; /*前一个对象的nextPerson存放的下一个对象的引用
							  (因为对象也是引用类型,相当于是引用的引用)*/
		}while(t!=firstPerson);
	}
}
public class CycleLinkTest{

	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		System.out.print("请输入环形链表的长度:");
		CycleLink t = new CycleLink();
		t.setLen(input.nextInt());	//给定环形链表的长度
		t.createLink();	//创建环链
		t.showLink(); //测试环链是否创建成功
	}
 }
 /*************************
 请输入环形链表的长度:6
1
2
3
4
5
6
 *************************/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章