1. 程式人生 > 其它 >哨兵節點(Sentinel Node)

哨兵節點(Sentinel Node)

Sentinel Node
紫色區域是何值並不關心
哨兵節點相當於一個啞單元,或者一個傀儡,作用是防止首節點為空時(first == null),出現無法指向下個節點情況。哨兵節點指向的下個單元為首節點。

public class SLList {
    public class IntNode {
        public int item;
        public IntNode next;
        public IntNode(int i, IntNode n) {
            item = i;
            next = n;
        }
    }

    private
IntNode first; private int size; public SLList() { first = null; size = 0; } public SLList(int x) { first = new IntNode(x, null); size = 1; } /** Adds an item to the front of the list. */ public void addFirst(int x) { first = new IntNode
(x, first); size += 1; } /** Retrieves the front item from the list. */ public int getFirst() { return first.item; } /** Returns the number of items in the list. */ public int size() { return size; } /** Adds an item to the end of the list. */
/* 這裡已經通過討論首節點為空的情況修正,但採用哨兵節點會更簡潔*/ public void addLast(int x) { size += 1; if(first == null){ first = new IntNode(x , first); return 0; IntNode p = first; while(p != null){ p = p.next; } p.next = IntNode(x , null); } /** Crashes when you call addLast on an empty SLList. Fix it. */ public static void main(String[] args) { SLList x = new SLList(); x.addLast(5); } }

新增節點的方法:

    public void addLast(int x) {
       size += 1;
        if(first == null){
            first = new IntNode(x , first);
            return 0;
        IntNode p = first;
        while(p != null){
            p = p.next;         
        }
        p.next = IntNode(x , null);
    }

利用哨兵節點進行優化:

    public void addLast(int x) {
    	size += 1;
        IntNode p = sentinel;
        while(p != null){
            p = p.next;         
        }
        p.next = IntNode(x , null);
    }

本文為CS61B學習筆記,參考連結:https://joshhug.gitbooks.io/hug61b/content/chap2/chap22.html