上一章:數據結構複習(5)—單鏈表
循環鏈表: 其實就是將 單鏈表 終端節點的(next)指針域,由單鏈表的 null 變爲指向頭節點,從而形成一個環。就變成了循環鏈表
與單鏈表 有 區別的代碼:
單鏈表: Node next = null ; 下一個指針域爲空
循環鏈表: LoopNode next = this; 指向自身
頭尾相連使得循環鏈表沒有明顯的尾端,可能會使一些方法進入死循環,一般判斷用作循環變量的工作指針是否等於某一個指針域(next)即可判斷是否遍歷了整個循環鏈表
之前單鏈表的時候遍歷都用了 while(true) ,直接用在循環鏈表肯定是死循環了
去掉查找所有
去掉判斷長度
去掉判斷最後一個節點
package cjy.datastructure;
/**
* 節點 Title: Node.java 循環鏈表
*
* @author CJY》10258
* @date 2019年7月12日
*/
public class LoopNode {
/**
* 節點對應的值(數值域)
*/
int data;
/**
* 下一個節點的位置(節點域) 默認指向自己
*/
LoopNode next = this;
/**
* 構建新節點
*
* @param data
* 節點的值
*/
public LoopNode(int data) {
this.data = data;
}
/**
* 轉到下一個節點位置
*
* @return
*/
public LoopNode next() {
return this.next;
}
/**
* 獲取當前節點的值
*
* @return
*/
public int getData() {
return this.data;
}
/**
* 在當前節點後面插入新節點
*
* @param newNode
*/
public void after(LoopNode newNode) {
LoopNode node = next;
this.next = newNode;
newNode.next = node;
}
/**
* 刪除當前節點的下一個節點
*/
public void removeNode() {
if (this.next == null) {
throw new RuntimeException("無下一個節點");
}
LoopNode node = next.next;
this.next = node;
}
}