创建环形链表

218 阅读1分钟

创建节点

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;
    }
}

创建环形链表

class CircleSingleLinkedList{
    创建一个first结点,当前没有编号
    private Boy first=new Boy(-1);
    public void addBoy(int nums){
        if (nums<1){
            System.out.println("nums的值不正确");
            return;
        }
        Boy curBoy=null;
        通过for循环来创建环形链表
        for (int i=1;i<=nums;i++){
            Boy boy=new Boy(i);
            if (i==1){
                first=boy;
                first.setNext(first);  此处连上第一个结点,从而构成环
                curBoy=first;
            }else {
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy=boy;            此处表示指针向后移
            }
        }
    }
    
    遍历环形链表
    public void showBoy(){
        if (first==null){
            return;
        }
        Boy curBoy=first;
        while (true){
            System.out.println(curBoy.getNo());
            if (curBoy.getNext()==first){
                break;
            }
            curBoy=curBoy.getNext();
        }
    }
}

测试

public class Test {
    public static void main(String[] args) {
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(5);     此处输入节点数
        circleSingleLinkedList.showBoy();
    }
}