1. 程式人生 > >【資料結構】單鏈表

【資料結構】單鏈表

我們單鏈表是一種鏈式存取的資料結構,用一組地址任意的儲存單元存放線性表中的資料元素。連結串列中的資料是以結點來表示的,每個結點的構成:元素(資料元素的映象) + 指標(指示後繼元素儲存位置),元素就是儲存資料的儲存單元,指標就是連線每個結點的地址資料。

我們應該也使用過LinkedList的集合,它就是一個連結串列的結構,接下來我們來手動實現一下單鏈表,這樣更加有利於瞭解其構成,首先建立一個Node單鏈表的節點

public class Node {
    //資料域
    public long data;
    //指標域
    public Node next;
    
    public
Node() { } public Node(long data) { this.data = data; } public void display(){ System.out.print(this.data + " "); } }

接下來我們建立一個單鏈表LinkList

public class LinkList {
    private Node first;

    /**
     * 插入一個節點,在頭節點結束後進行插入
     * @param value
     */
    public void
insertFirst(long value){ Node node = new Node(value); node.next = first; first = node; } /** * 刪除一個節點,在頭節點結束後進行刪除 */ public Node deleteFirst(){ Node tmp = first; first = tmp.next; return tmp; } /** * 遍歷連結串列 */ public
void display(){ Node current = first; while (current != null){ current.display(); current = current.next; } System.out.println(); } /** * 查詢 * @param value * @return */ public Node find(long value){ Node current = first; while (current.data != value){ if (current.next == null) return null; current = current.next; } return current; } /** * 刪除方法,根據資料刪除 * 找到它前面的節點 * @param value * @return */ public Node delete(long value){ Node current = first; Node prev = first; while (current.data != value){ if (current.next == null) return null; prev = current; current = current.next; } if (current == first){ first = first.next; }else{ prev.next = current.next; } return current; } }

接下來編寫測試類進行測試

public class TestLinkList {
    public static void main(String[] args) {
        LinkList linkList = new LinkList();
        //插入
        linkList.insertFirst(34);
        linkList.insertFirst(23);
        linkList.insertFirst(12);
        linkList.insertFirst(2);
        linkList.insertFirst(3);
        //遍歷
        linkList.display();
        //刪除頭部
        linkList.deleteFirst();
        linkList.display();
        //查詢
        Node node = linkList.find(23);
        node.display();
        System.out.println();
        //刪除指定值
        Node delNode = linkList.delete(23);
        linkList.display();
    }
}

執行結果如下:
執行結果