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