小言_互联网的博客

JAVA--约瑟夫链表--有图

283人阅读  评论(0)
import java.util.Scanner;

/**
 * @author:Ravanla
 * @vreate:2019-10-15-18:43
 */
public class YueSeFu {
    Scanner sc = new Scanner(System.in);
    Node head;
    Node tail;

    public YueSeFu(){
        head = new Node();
        tail = head;
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int m = sc.nextInt();
        y.Create(n,k,m);
    }

创建一个循环链表

    void Create(int n,int k,int m){
        Node temp = head;
        for(int i = 1; i < n ; i++){
            Node p = new Node();
            p.data = i;
            temp.next = p;
            temp = p;
        }// 头插入 , 插入剩下最后一个 , 让它的next指向head
        // 下面就是让它指向head
        Node p = new Node();
        p.data = n;
        temp.next = p;
        p.next = head.next;
//        Print();// 打印循环链表,可以看看效果
        DeleteYSF(k,m);
    }
    void DeleteYSF(int k, int m){// 从第k个开始删除,
    // 每m个就删除一次,删除之前打印一下删除的数据
        Node prev = head;// prev是d 的前驱节点
        Node d = prev.next;
        for(int i = 1; i < k; i++){
            prev = d;
            d = d.next;
        }
        System.out.print(d.data + " ");
        Delete(prev);
        d = prev.next;
        while(prev != d){
            for(int i = 1; i < m; i++){
                prev = d;
                d = d.next;
            }
            System.out.print(d.data + " ");
            Delete(prev);
            d = prev.next;
        }
        System.out.print(d.data + " ");
    }

这里红色的框框是第k的人

每隔m个人也是这样找的

    void Delete(Node e){
        e.next = e.next.next;
    }

    void Print(){
        Node temp = head.next;
        while(temp.next.data != 1){
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println(temp.data);
    }

    public static void main(String[] args) {
        YueSeFu y = new YueSeFu();
    }

    class Node{
        int data;
        Node next;
    }
}

转载:https://blog.csdn.net/weixin_43584220/article/details/102567205
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场