java学习 使用循环链表解决约瑟夫问题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java学习 使用循环链表解决约瑟夫问题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1939字,纯文字阅读大概需要3分钟。
内容图文
public class Josefu {
public static void main(String[] args) {
CirSingleLinked cir = new CirSingleLinked();
//500个小孩
cir.addBoy(500);
//从第一个开始数,每数到3,出圈
cir.countBoy(1, 3, 500);
}
}
class CirSingleLinked {
private Boy first = null;
public boolean isEmpty() {
return first == null;
}
public void list() {
if (isEmpty()) {
System.out.println("链表为空!");
return;
}
Boy curBoy = first;
while (true) {
System.out.println(curBoy);
if (curBoy.getNext() == first)
break;
curBoy = curBoy.getNext();
}
}
// 添加小孩节点
public void addBoy(int nums) {
if (nums < 1) {
System.out.println("请输入大于0的数");
return;
}
// 辅助指针,帮助构建环形链表
Boy curBoy = null;
for (int i = 1; i <= nums; i++) {
if (i == 1) {
// 第一个结点next指向自己
first = new Boy(i);
first.setNext(first);
curBoy = first;
continue;
}
// 生成新的Boy结点
Boy newBoy = new Boy(i);
curBoy.setNext(newBoy);
newBoy.setNext(first);
curBoy = newBoy;
}
}
/**
* 需创建一个辅助指针来进行出圈
* @param startNo 从第几个小孩开始数数
* @param countNum 表示 数几下
* @param nums表示最初有多少个小孩在圈中
*/
public void countBoy(int startNo, int countNum, int nums) {
if (first == null || startNo < 1 || startNo > nums) {
System.out.println("数据录入有误,请重新输入");
return;
}
//first 指向startNo小孩 移动 startNo-1次
for (int i = 1; i < startNo; i++) {
first = first.getNext();
}
//出圈
//循环操作 直到圈中只有一个结点
while(true) {
if(first.getNext() == first) break;
//小孩报数时, first移动到要删除的小孩前一位值,然后删除
for(int i = 1; i< countNum -1 ;i++) {
first = first.getNext();
}
System.out.println(first.getNext());
first.setNext(first.getNext().getNext());
first = first.getNext();
}
System.out.println(first);
}
}
class Boy {
private int no;
private Boy next;
public Boy(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
@Override
public String toString() {
return "Boy [no=" + no + "]";
}
}
内容总结
以上是互联网集市为您收集整理的java学习 使用循环链表解决约瑟夫问题全部内容,希望文章能够帮你解决java学习 使用循环链表解决约瑟夫问题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。