class Node{
public Object data;
public Node next;
public Node getNext() {
return next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
Node(){
super();
}
public Node(Object data, Node next){
super();
this.data=data;
this.next=next;
}
}
public class YueSeFu{
public static void main(String[] args) {
Node node1=new Node("1",null);
Node node2=new Node("2",null);
Node node3=new Node("3",null);
Node node4=new Node("4",null);
Node node5=new Node("5",null);
Node node6=new Node("6",null);
Node node7=new Node("7",null);
Node header = node1;
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
node7.next = node1;
teat(header);
}
private static void teat(Node header) {
Node n = header;
Node lastOne ;//表示上一个节点
int count = 1 ;
System.out.print("依次出列的顺序为:");
while(n != n.next){//最后环中只剩下一个人,那肯定是它的下一个就是它本身 即 n=n.next
lastOne = n;
n = n.next;
count ++ ;
if(count == 3){//若数到3,出列
lastOne.next = n.next;//上一个的节点的下一个就是当前的下一个 即lastOne.next = n.next;
count = 0;//count清 0
System.out.print(n.data + " ");//打印出列的元素
}
}
System.out.println();
System.out.println("最后剩下的是:" + n.data);
}
}
算法学习Day-2 使用链表解决约瑟夫环
最新推荐文章于 2023-03-18 19:25:10 发布