1 //结点类 2 package cn.ftf.mylinklist; 3 public class Node { 4 public Object obj; 5 public Node next; 6 public Node() { 7 super(); 8 } 9 public Node(Object obj, Node next) { 10 super(); 11 this.obj = obj; 12 this.next = next; 13 } 14 public Node(Object obj) { 15 super(); 16 this.obj = obj; 17 } 18 }
1 package cn.ftf.mylinklist; 2 /* 3 * 手写约瑟夫环,用结点类代替小孩 4 */ 5 6 //单向循环链表类 7 public class CircularLinkList { 8 Node firstNode=null; 9 int count=0; 10 11 public CircularLinkList(int count) { 12 this.count = count; 13 addNode(count); 14 } 15 public void addNode(int aa){ 16 Node temp=null; 17 for(int i=1;i<=aa;i++) { 18 if(i==1) { 19 firstNode=new Node(i); 20 temp=firstNode; 21 temp.next=firstNode; 22 System.out.print(" +"+i); 23 }else { 24 System.out.print(" +"+i); 25 temp.next=new Node(i); 26 temp=temp.next; 27 temp.next=firstNode; 28 } 29 } 30 System.out.println(); 31 } 32 public void out(int count,Node node) { 33 Node temp=node; 34 for(int i=1;i<count;i++) { 35 temp=temp.next; 36 } 37 System.out.print(temp.next.obj+"->"); 38 temp.next=temp.next.next; 39 } 40 public void outNode(int c) { 41 int sum=1; 42 Node temp=firstNode; 43 while(temp.next!=temp) { 44 temp=temp.next; 45 sum++; 46 if(sum==c) { 47 out(count,temp); 48 count--; 49 sum=0; 50 } 51 } 52 System.out.println(temp.obj); 53 } 54 55 56 57 58 public static void main(String[] args) { 59 CircularLinkList cir=new CircularLinkList(20); 60 cir.outNode(5); 61 } 62 }
测试结果:
来源:博客园
作者:房廷飞
链接:https://www.cnblogs.com/fangtingfei/p/11432514.html