1. 程式人生 > >循環單鏈表(七)

循環單鏈表(七)

pri 插入 你會 ext nbsp out 元素 初始 刪除節點

循環單鏈表和單鏈表最大的區別是它的某個節點會指向該鏈表的頭節點。通過循環你會發現該鏈表循環不盡,整個鏈表形成一個環。

循環鏈表插入元素

1、找到該鏈表的下一個節點

2、新元素的下一個節點指向該鏈表的下一個節點。

3、該鏈表的下個節點指向新元素。

代碼

public class LoopNode {

    int data;
    //循環鏈表初始化 next默認為自身
    LoopNode next = this;


       public LoopNode after(LoopNode node) {
        LoopNode nextNodes 
= this.next; // 直接插入在當前節點後面 無法循環到最後一個 node.next = nextNodes; // 最後一個節點下一個節點指向 node this.next = node; // 循環列表 return this; } }

刪除節點

1、找到該元素的下下個節點。

2、當前鏈表的下個節點指向下下個節點。

代碼

public class LoopNode {

    int data;
    //循環鏈表初始化 next默認為自身
    LoopNode next = this
; // 刪除節點 public void remove() { // 先取出下下個節點 LoopNode nextNode = next().next(); this.next = nextNode; } }

所有代碼

public class LoopNode {

    int data;
    //循環鏈表初始化 next默認為自身
    LoopNode next = this;

    public LoopNode(int data) {
        this.data = data;
    }

    
public LoopNode after(LoopNode node) { LoopNode nextNodes = this.next; // 直接插入在當前節點後面 無法循環到最後一個 node.next = nextNodes; // 最後一個節點下一個節點指向 node this.next = node; // 循環列表 return this; } // 刪除節點 public void remove() { // 先取出下下個節點 LoopNode nextNode = next().next(); this.next = nextNode; } public LoopNode next() { return this.next; } public int getData() { return data; } }

測試代碼

public class NodeTest {

    public static void main(String[] args) {
        LoopNode loopNode1 = new LoopNode(1);
        LoopNode loopNode2 = new LoopNode(2);
        LoopNode loopNode3 = new LoopNode(3);
        loopNode1.after(loopNode2);
        loopNode2.after(loopNode3);
        System.out.println(loopNode1.next.next.getData());

    }
}

循環單鏈表(七)