栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

数据结构:循环链表

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构:循环链表

public class Student {
    int no;
    Student next;

    public Student() {
    }

    public Student(int no) {
        this.no = no;
    }


    @Override
    public String toString() {
        return "Student{" +
                "no=" + no +
                '}';
    }
}
public class list {
    Student first;

    public void add(int num) {
        if (num < 1) {
            System.out.println("学生的数量不合理");
        }
        Student cur = null;
        for (int x = 1; x <= num; x++) {
            Student s = new Student(x);
            if (x == 1) {
                first = s;
                s.next = s;
                cur = first;
            } else {
                cur.next = s;
                s.next = first;
                cur = s;
            }
        }
    }

    public void show() {
        if (first == null) {
            System.out.println("链表为空");
        }
        Student cur = first;
        while (true) {
            System.out.println(cur);
            if (cur.next == first) {
                break;
            }
            cur = cur.next;
        }
    }

    public void order(int k, int m, int sum) {
        if (first == null || k < 1 || m > sum) {
            System.out.println("数据输入有误");
        }
        //找到编号为k的人cur
        Student cur = first;
        while (true) {
            if (cur.no == k) {
                break;
            }
            cur = cur.next;
        }
        StringBuilder sb = new StringBuilder();

        while (cur.next != cur) {
            //找到从k开始,数到m的前一个人
            for (int x = 1; x <= m - k - 1; x++) {
                cur = cur.next;
            }
            //先记录下来移除的人的编号
            sb.append(cur.next.no);
            //把此时的cur的后一个人移除
            cur.next = cur.next.next;
            //从此时cur的后一个人开始报1,接着找数到m的人
            cur = cur.next;
        }
        //此时只剩下cur
        sb.append(cur.no);
        System.out.println(sb);
    }
}

public class Demo {
    public static void main(String[] args) {
        list list=new list();
        list.add(6);
        list.show();
        list.order(6, 2, 6);//135264
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/733130.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号