Josephus环类问题,java实现
2015-11-06 17:35
330 查看
写出一个双向的循环链表,弄一个计数器,我定义的是到三的时候,自动删除当前节点,很简单。
package Com; import java.util.Scanner; /* * 约瑟夫环问题,有n个人组成的圈,数到3的那个人出列,下个人继续从一开始 */ public class Josephus { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = Integer.parseInt(s.nextLine()); Node first = new Josephus().startRun(n ); int count = 1; while(first.next != first) { first = first.next; count++; if(count == 3) { first.previous.next = first.next; first.next.previous = first.previous; first = first.next; count = 1; } } System.out.println("最后剩下来的数字为:"+first.n); } public Node startRun(int n) { Node first = new Node(); first.previous = null; first.n = n ; //这里给链表赋值,倒叙 Node current = first; Node last = first; while((--n)>0) { current.next = new Node(); current = current.next; current.n = n; current.previous = last; last = current; } current.next = first; first.previous = current; return first; } class Node { int n ; Node next; Node previous; } }
相关文章推荐
- 服务端工程师入门与进阶 Java 版
- JavaScirpt学习经历
- Java读取properties配置文件时,中文乱码解决方法
- spring ioc原理(看完后大家可以自己写一个spring)
- kettle crontab java: command not found
- myeclipse三个地方的java版本统一
- Spring 整合 Mina
- Java的IO流的操作和一些理解
- Javapns-sdk16-2.2.1多线程推送
- java 参数传递 空对象 null
- Spring使用session,request,global sessiong作用域出现异常解决方法
- Java:类与继承
- 实战企业项目--springMVC+Mybatis
- Java编程中的异常和错误你遇到过哪些?
- java中HashSet详解
- java核心技术 要点笔记3
- SpringMVC在Controller层实现aop,同类中方法调用问题
- 关于java.io.IOException: open failed: EACCES (Permission denied)问题的解决
- java学习 大问题 @Service @Autowired @Override spring的装配
- Ehcache 整合Spring 使用页面、对象缓存