/**
* @Description 定義一個循環鏈表
* @auther Eleven
* @create 2020-04-03 21:33
**/
public class LoopNode {
//用於存儲鏈表裏面的數據
int data;
//這裏如果是定義一個單獨的node時,要將這個指向自身
LoopNode next = this;
//用於初始化的時候給node中保存數據
public LoopNode(int data) {
this.data = data;
}
//刪除節點
public void remove(LoopNode node){
//找到要刪除節點的下一個節點
LoopNode nextNode = node.next();
//定義變量接受當前節點
LoopNode currentNode = this;
//循環判斷當前節點的下一個節點是否等於要移除的節點,如果不等於就繼續循環,如果等於就跳出循環
while(currentNode.next != node){
//不等於就把當前的節點的下一個節點賦給當前節點
currentNode = this.next;
}
currentNode.next = nextNode;
}
//添加鏈表中的節點 就是將當前節點的下一個節點指向該節點,原下一個節點改爲新增加的這個節點的下一個節點
public void after(LoopNode node){
//定義變量接受當前節點
LoopNode currentNode = this;
//獲取原先當前節點的下一個節點
LoopNode nextNext = currentNode.next;
//當前節點的下一個節點設置爲新的節點
this.next = node;
//新節點的下一個節點設置爲原先節點的下一個節點
node.next=nextNext;
}
//獲取當前節點中的數據
public int getData(){
return this.data;
}
//獲取當前節點的下一個節點
public LoopNode next(){
return this.next;
}
}
測試用例:
class Test01{
public static void main(String[] args) {
LoopNode l1 = new LoopNode(1);
LoopNode l2 = new LoopNode(2);
LoopNode l3 = new LoopNode(3);
LoopNode l4 = new LoopNode(4);
l1.after(l2);
l2.after(l3);
l3.after(l4);
System.out.println(l1.next.getData());
System.out.println(l2.next.getData());
System.out.println(l3.next.getData());
System.out.println(l4.next.getData());
}
}