Java 环形单链表解决约瑟夫问题
标签:style list head lse size 初始 new 总数 读取
环形单链表解决约瑟夫问题
package linkedlist;
public class Josephu {
private Node head;
private int size = 0;
/**
* 约瑟夫问题
* 输入数据的总数直接从size中读取,可以不显示的指定
* 删除数到的节点
*
* @param startNum 从第几个元素开始数
* @param countNum 数几下
*/
public void count(int startNum, int countNum) {
if (startNum > size || startNum ) {
System.out.printf("param is invalid");
return;
}
// temp指向待删除元素的前一根元素,初始化为head的前一个元素
Node temp = head;
for (int i = 0; i ) {
temp = temp.next;
}
// 头节点置位null,这样才可以删除头节点指向的元素
head = null;
//temp指向数数的起点的前一个元素
for (int i = 0; i ) {
temp = temp.next;
}
// 计数器
int skipCount = 0;
// 总共会输出size个元素
while (size > 0) {
// 环形链表内循环数数,数到第countNum的元素删除
for (int i = 0; i ) {
if (skipCount + 1 == countNum) {
System.out.print(temp.next.item + " ");
skipCount = 0;
temp.next = temp.next.next;
size--;
} else {
skipCount++;
temp = temp.next;
}
}
}
System.out.println();
}
public int getSize() {
return size;
}
public void print() {
Node temp = head;
for (int i = 0; i null != temp; i++) {
System.out.printf(temp.item + " ");
temp = temp.next;
}
System.out.println();
}
public void add(T data) {
Node newData = new Node(data, null);
Node temp = head;
for (int i = 0; i ) {
temp = temp.next;
}
// 链表为空处理
if (null == temp) {
head = newData;
newData.next = head;
} else {
// 插入数据到链表的尾部
temp.next = newData;
newData.next = head;
}
size++;
}
private static class Node {
T item;
Node next;
public Node(T item, Node next) {
this.item = item;
this.next = next;
}
}
}
Java 环形单链表解决约瑟夫问题
标签:style list head lse size 初始 new 总数 读取
原文地址:https://www.cnblogs.com/6xiong/p/13205859.html
评论