本文共 3221 字,大约阅读时间需要 10 分钟。
关于单向环形链表的实际应用,先看一下下面这道题
接下来,我们先简单分析一下单向环形链表的demo 构建一个单向环形链表的思路 1)先创建第一个节点,让first指向该节点,并形成环. 2)后面当我们没创建一个节点,就把该节点,加入到已有的环形链表即可.遍历环形链表
1)先让一个辅助指针(变量)curBoy,指向first节点 2)然后通过一个while循环遍历该环形链表即可.package com.dataStructure.com.dataStructure.linklist;public class Josepfu { public static void main(String[] args) { CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList(); circleSingleLinkedList.addBoy(5); circleSingleLinkedList.showBoy(); }}//创建一个单向环形链表class CircleSingleLinkedList{ //创建first节点,当前没有编号 private Boy first = null; //添加节点,构建成一个环形的链表 public void addBoy(int nums){ if(nums < 1){ System.out.println("nums value id incorrect"); return; } Boy curBoy = null; for (int i = 1; i <= nums; i++) { Boy boy = new Boy(i); if(i == 1){ first = boy; first.setNext(first); curBoy = boy; }else{ curBoy.setNext(boy); boy.setNext(first); curBoy = boy; } } } //遍历当前链表 public void showBoy(){ if(first == null){ System.out.println("linkedlist is null"); return; } Boy curBoy = first; while (true){ System.out.println(curBoy.getNo()); if(curBoy.getNext() == first){ break; } curBoy = curBoy.getNext(); } }}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; } @Override public String toString() { return "Boy{" + "no=" + no + ", next=" + next + '}'; }}
接下来将文章最开始的题解决掉,解决问题分析
(1)需求创建一个辅助指针(变量)helper,事先应该指向环形链表的最后这个节点. (2)报数之前,先让first和helper移动k-1次 (3)当报数时,让first和helper指针同时移动m-1次 (4)这时就可以将first指向小孩节点出圈 first = first.next helper.next = firstpublic void countBoy(int startNo,int countNo,int nums){ //先对数据进行校验 if(first == null || startNo < 1 || startNo > nums){ System.out.println("input data incorrect"); return; } //创建辅助指针 Boy helper = first; //创建辅助指针helper,事先指向环形链表的最后节点 while (true){ if(helper.getNext() == first){ break; } helper = helper.getNext(); } //先让first和helper移动startNo-1次 for (int i = 0; i < startNo - 1 ; i++) { first = first.getNext(); helper = helper.getNext(); } //first和helper同时移动countNo-1次,然后出圈 while (true){ if(helper == first){ //说明圈中只有一个节点 break; } for (int i = 0; i < countNo - 1 ; i++) { first = first.getNext(); helper = helper.getNext(); } System.out.println("出圈的是"+first.getNo()); first = first.getNext(); helper.setNext(first); } System.out.println("the last is" + first.getNo()); }
转载地址:http://djmzi.baihongyu.com/