class MM{
public static void main(String[] args){
singleCircleNode list=new singleCircleNode();
// list.creatAndFind(1,1,5);//实现直接创建环,解决约瑟夫问题
//实现创建链表后添加 //先创建再添加的功能
list.creat(10);
list.showList();
System.out.println("--------------------");
list.add(10);
list.showList();
}
}
class singleCircleNode{
Node head=new Node(1);
Node temp=head;
public void creat(int num){
if(num<1){
System.out.println("参数不正确");
return;
}
if(num==1){
head.setNext(head);
}else {
int n=2;
while (num>1){
Node node=new Node(n);
temp.setNext(node);
temp =temp.getNext();
num--;
n++;
}
temp.setNext(head);
}
}
public void add(int number){
int n=temp.getNo()+1;
while (number>0){
Node node=new Node(n);
temp.setNext(node);
temp=temp.getNext();
number--;
n++;
}
temp.setNext(head);
}
public void showList(){
Node temp=head;
while (true){
System.out.println(temp);
temp=temp.getNext();
if(temp==head)break;
}
}
public void creatAndFind(int startNum,int step,int Num){
if(startNum>Num||step<1||Num<1){
System.out.println("参数不正确");
if(startNum>Num){
System.out.println("开始号码不能大于最大号码");
}
if(step<1){
System.out.println("步数需要大于1");
}
if(Num<1){
System.out.println("长度需要至少为1");
}
return;
}
//创建环
Node temp1=head;
if(Num==1){
head.setNext(head);
}else {
int n=2;
while (Num>1){
Node node=new Node(n);
temp1.setNext(node);
temp1 =temp1.getNext();
Num--;
n++;
}
temp1.setNext(head);
}
//找到开始位置
while (true){
if(temp1.getNo()==startNum){
System.out.println("找到了开始位置!");
System.out.println(temp1);
break;
}
temp1=temp1.getNext();
}
while (true){
if(temp1.getNext()==temp1){
System.out.println("最终的号码"+temp1);
break;
}
for(int i=0;i<step-1;i++){
temp1=temp1.getNext();
}
//找到了待删除的上一个节点
//删除节点
System.out.println("删除的节点"+temp1.getNext());
temp1.setNext(temp1.getNext().getNext());
temp1=temp1.getNext();
}
}
}
class Node {
private int no;
private Node next;
public Node(int i) {
this.no=i;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
'}';
}
}
单向环形链表 约瑟夫问题
最新推荐文章于 2022-11-27 18:19:15 发布