我就在这用链表来做了
- public static String getRing2(int total,int m,boolean isAll){
- LinkedList<Integer> container=new LinkedList<Integer>();
- for(int i=1;i<=total;i++)
- container.add(i);
- //初始化集合完成。
- int count=1;//count用于数数,从1数到m。
- StringBuilder result=new StringBuilder();
- String temp="";
- while(container.size()!=1){//一直数数,剔除目标元素,直到容器内只剩一个元素
- for(int num=0;num<container.size();num++){//num用于遍历容器内的每一个元素
- /*数到m,则剔除容器的内的当前元素
- 由于link集合剔除一个元素,意味着后面所有元素的角标-1,所以让num在剔除后自减
- 将count置0,下次循环继续从1开始数数。*/
- if(count==m){
- temp=container.remove(num--)+",";
- if(isAll)
- result.append(temp);
- count=0;
- }
- count++;
- }
- }
- result.append(container.remove());
- return result.toString();
- }
- public static String getRing3(int totalNum ,int m,boolean isAll){
- class Node{
- public int number;// 编号
- public Node next;// 下一个节点
- public Node(int number){
- this.number = number;
- }
- }
- Node header = new Node(1);
- Node pointer = header;
- for (int i = 2; i <= totalNum; i++) {
- pointer.next = new Node(i);
- pointer = pointer.next;
- }
- pointer.next = header;
- // 初始化环形链表结束
- StringBuilder result=new StringBuilder();
- while (pointer != pointer.next) {
- for (int i = 1; i < m; i++)
- pointer = pointer.next;
- if(isAll)
- result.append(pointer.next.number+",");
- pointer.next = pointer.next.next;
- }
- result.append(pointer.next.number);
- return result.toString();
- }
复制代码 |