单项环形链表介绍
是一种物理存储单元上非连续,非顺序的存储结构(能有效利用内存碎片)。数据的逻辑顺序通过链表中的指针来实现。
约瑟夫(Josephus)问题
设编号为1,2,...n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,依次类推,直到所有人都出列为止,由此产生一个出队列编号的序列。
代码实现(提示:需要两个指针操作)
public class Josephu {
public static void main(String[] args) {
AnnularLinkedList linkedList = new AnnularLinkedList();
linkedList.add(5);
linkedList.show();
linkedList.countNode(5,2,3);
}
}
class AnnularLinkedList{
//第一个节点
private Node first = null;
//临时指针变量
private Node temp = null;
/**
* 添加节点
*/
public void add(int count){
if (count < 1){
System.out.println("传入的数量不正确");
return;
}
for (int i=1;i<=count;i++){
Node node = new Node(i);
if (i == 1){
first = node;
first.setNext(first);
temp = first;
}else {
temp.setNext(node);
node.setNext(first);
temp = node;
}
}
}
public void show(){
temp = first;
while (true){
if (temp.getNext() == first){
System.out.println(temp.getVal());
break;
}
System.out.println(temp.getVal());
temp = temp.getNext();
}
}
public void countNode(int totalNo ,int startNO, int num){
//添加节点
add(totalNo);
temp = first;
//约定编号为k的人
while (true){
if (temp.getVal() == startNO){
first = temp;
break;
}
temp = temp.getNext();
}
while (true){
if (temp.getNext() == temp){
break;
}
for (int i = 1; i < num; i++) {
temp = first;
first = first.getNext();
}
System.out.println("当前节点为:"+first.getVal());
//进行节点去除
temp.setNext(first.getNext());
first = temp.getNext();
}
System.out.println("最后一个节点为:"+first.getVal());
}
}
class Node{
private int val;
private Node next;
public Node(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}