//创建一个环形的单向链表 classCircleSingleLinkedList{ //创建一个first节点,当前没有编号 private Boy first = null; //添加小孩节点,构件成一个环形的链表 publicvoidaddBoy(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; } } }
//遍历当前的环形链表 publicvoidshowBoys(){ //判断链表是否为空 if (first == null) { System.out.println("没有任何小孩"); return; } //因为first不能动,因此我们仍然使用一个辅助指针完成遍历 Boy curBoy = first; do { System.out.println("小孩编号:" + curBoy.getNo()); curBoy = curBoy.getNext(); } while (curBoy != first); } }
/** * 创建一个Boy,表示一个节点 */ classBoy{ privateint no; private Boy next;
publicBoy(int no){ this.no = no; }
publicBoy(int no, Boy next){ this.no = no; this.next = next; } //set/get省略了... @Override public String toString(){ return"Boy{" + "no=" + no + '}'; } }