第4章 最基礎的動態數據結構:鏈表

4-1 什麼是鏈表

在這裏插入圖片描述
爲什麼鏈表很重要

  • 鏈表:真正的動態數據結構
  • 最簡單的動態數據結構
  • 更深入的理解引用(或者指針)
  • 更深入的理解遞歸
  • 輔助組成其他數據結構

鏈表

數據存儲在"節點(Node)中

class Node {
	E e;
	Node next;
}

在這裏插入圖片描述
優點:真正的動態,不需要處理固定容量的問題
缺點:喪失了隨機訪問的能力

數組與鏈表的對比

數組 鏈表
數組最好用於索引有語意的情況。scores[2] 鏈表不適合索引有語意的情況
支持快速查詢 動態
public class LinkedList<E> {

    private class Node{
        public E e;
        public Node next;

        public Node(E e, Node next){
            this.e = e;
            this.next = next;
        }

        public Node(E e){
            this(e, null);
        }

        public Node(){
            this(null, null);
        }

}

4-2 鏈表Linked List

在鏈表頭添加元素

在這裏插入圖片描述

    // 在鏈表頭添加新的元素e
    public void addFirst(E e){
//        Node node = new Node(e);
//        node.next = head;
//        head = node;

        head = new Node(e, head);
        size ++;
    }

在鏈表中間和末尾添加元素

在這裏插入圖片描述
在這裏插入圖片描述

    // 在鏈表的index(0-based)位置添加新的元素e
    // 在鏈表中不是一個常用的操作,練習用:)
    public void add(int index, E e){

        if(index < 0 || index > size)
            throw new IllegalArgumentException("Add failed. Illegal index.");

        if(index == 0)
            addFirst(e);
        else{
            Node prev = head;
            for(int i = 0 ; i < index - 1 ; i ++)
                prev = prev.next;

//            Node node = new Node(e);
//            node.next = prev.next;
//            prev.next = node;

            prev.next = new Node(e, prev.next);
            size ++;
        }
    }
        // 在鏈表末尾添加新的元素e
    public void addLast(E e){
        add(size, e);
    }

4-3 使用鏈表的虛擬頭結點

在這裏插入圖片描述

public class LinkedList<E> {

    private class Node{
        public E e;
        public Node next;

        public Node(E e, Node next){
            this.e = e;
            this.next = next;
        }

        public Node(E e){
            this(e, null);
        }

        public Node(){
            this(null, null);
        }

        @Override
        public String toString(){
            return e.toString();
        }
    }

    private Node dummyHead;
    private int size;

    public LinkedList(){
        dummyHead = new Node();
        size = 0;
    }

    // 獲取鏈表中的元素個數
    public int getSize(){
        return size;
    }

    // 返回鏈表是否爲空
    public boolean isEmpty(){
        return size == 0;
    }

    // 在鏈表的index(0-based)位置添加新的元素e
    // 在鏈表中不是一個常用的操作,練習用:)
    public void add(int index, E e){

        if(index < 0 || index > size)
            throw new IllegalArgumentException("Add failed. Illegal index.");

        Node prev = dummyHead;
        for(int i = 0 ; i < index ; i ++)
            prev = prev.next;

        prev.next = new Node(e, prev.next);
        size ++;
    }

    // 在鏈表頭添加新的元素e
    public void addFirst(E e){
        add(0, e);
    }

    // 在鏈表末尾添加新的元素e
    public void addLast(E e){
        add(size, e);
    }
}

4-4 鏈表的遍歷,查詢和修改

// 獲得鏈表的第index(0-based)個位置的元素
    // 在鏈表中不是一個常用的操作,練習用:)
    public E get(int index){

        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Get failed. Illegal index.");

        Node cur = dummyHead.next;
        for(int i = 0 ; i < index ; i ++)
            cur = cur.next;
        return cur.e;
    }

    // 獲得鏈表的第一個元素
    public E getFirst(){
        return get(0);
    }

    // 獲得鏈表的最後一個元素
    public E getLast(){
        return get(size - 1);
    } 
    // 修改鏈表的第index(0-based)個位置的元素爲e
    // 在鏈表中不是一個常用的操作,練習用:)
    public void set(int index, E e){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Set failed. Illegal index.");

        Node cur = dummyHead.next;
        for(int i = 0 ; i < index ; i ++)
            cur = cur.next;
        cur.e = e;
    }
    // 查找鏈表中是否有元素e
    public boolean contains(E e){
        Node cur = dummyHead.next;
        while(cur != null){
            if(cur.e.equals(e))
                return true;
            cur = cur.next;
        }
        return false;
    }

4-5 從鏈表中刪除元素

在這裏插入圖片描述

    // 從鏈表中刪除index(0-based)位置的元素, 返回刪除的元素
    // 在鏈表中不是一個常用的操作,練習用:)
    public E remove(int index){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Remove failed. Index is illegal.");

        Node prev = dummyHead;
        for(int i = 0 ; i < index ; i ++)
            prev = prev.next;

        Node retNode = prev.next;
        prev.next = retNode.next;
        retNode.next = null;
        size --;

        return retNode.e;
    }

    // 從鏈表中刪除第一個元素, 返回刪除的元素
    public E removeFirst(){
        return remove(0);
    }

    // 從鏈表中刪除最後一個元素, 返回刪除的元素
    public E removeLast(){
        return remove(size - 1);
    }

    // 從鏈表中刪除元素e
    public void removeElement(E e){

        Node prev = dummyHead;
        while(prev.next != null){
            if(prev.next.e.equals(e))
                break;
            prev = prev.next;
        }

        if(prev.next != null){
            Node delNode = prev.next;
            prev.next = delNode.next;
            delNode.next = null;
            size --;
        }
    }

鏈表的時間複雜度分析

添加操作 時間複雜度
addLast(e) O(n)
addFirst(e) O(1)
add(index,e) O(n/2)=O(n)
綜合 O(n)
刪除操作 時間複雜度
removeLast(e) O(n)
removeFirst(e) O(1)
remove(index,e) O(n/2)=O(n)
綜合 O(n)
修改操作 時間複雜度
set(index,e) O(n)
查找操作 時間複雜度
get(index) O(n)
contains(e) O(n)

在這裏插入圖片描述

4-6 使用鏈表實現棧

public class LinkedListStack<E> implements Stack<E> {

    private LinkedList<E> list;

    public LinkedListStack(){
        list = new LinkedList<>();
    }

    @Override
    public int getSize(){
        return list.getSize();
    }

    @Override
    public boolean isEmpty(){
        return list.isEmpty();
    }

    @Override
    public void push(E e){
        list.addFirst(e);
    }

    @Override
    public E pop(){
        return list.removeFirst();
    }

    @Override
    public E peek(){
        return list.getFirst();
    }

4-7 帶有尾指針的鏈表:使用鏈表實現隊列

public class LinkedListQueue<E> implements Queue<E> {

    private class Node{
        public E e;
        public Node next;

        public Node(E e, Node next){
            this.e = e;
            this.next = next;
        }

        public Node(E e){
            this(e, null);
        }

        public Node(){
            this(null, null);
        }

        @Override
        public String toString(){
            return e.toString();
        }
    }

    private Node head, tail;
    private int size;

    public LinkedListQueue(){
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public int getSize(){
        return size;
    }

    @Override
    public boolean isEmpty(){
        return size == 0;
    }

    @Override
    public void enqueue(E e){
        if(tail == null){
            tail = new Node(e);
            head = tail;
        }
        else{
            tail.next = new Node(e);
            tail = tail.next;
        }
        size ++;
    }

    @Override
    public E dequeue(){
        if(isEmpty())
            throw new IllegalArgumentException("Cannot dequeue from an empty queue.");

        Node retNode = head;
        head = head.next;
        retNode.next = null;
        if(head == null)
            tail = null;
        size --;
        return retNode.e;
    }

    @Override
    public E getFront(){
        if(isEmpty())
            throw new IllegalArgumentException("Queue is empty.");
        return head.e;
    }
}

4-8 LeetCode中和鏈表相關的問題

LeetCode203
Solution1——不使用虛擬頭節點

class Solution {

    public ListNode removeElements(ListNode head, int val) {

        while(head != null && head.val == val){
            ListNode delNode = head;
            head = head.next;
            delNode.next = null;
        }

        if(head == null)
            return head;

        ListNode prev = head;
        while(prev.next != null){
            if(prev.next.val == val) {
                ListNode delNode = prev.next;
                prev.next = delNode.next;
                delNode.next = null;
            }
            else
                prev = prev.next;
        }

        return head;
    }
}

Solution2——使用虛擬頭節點

class Solution {

    public ListNode removeElements(ListNode head, int val) {

        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;

        ListNode prev = dummyHead;
        while(prev.next != null){
            if(prev.next.val == val)
                prev.next = prev.next.next;
            else
                prev = prev.next;
        }

        return dummyHead.next;
    }
}

4-9 測試自己的LeetCode鏈表代碼

class Solution {

    public ListNode removeElements(ListNode head, int val) {

        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;

        ListNode prev = dummyHead;
        while(prev.next != null){
            if(prev.next.val == val)
                prev.next = prev.next.next;
            else
                prev = prev.next;
        }

        return dummyHead.next;
    }

    public static void main(String[] args) {

        int[] nums = {1, 2, 6, 3, 4, 5, 6};
        ListNode head = new ListNode(nums);
        System.out.println(head);

        ListNode res = (new Solution3()).removeElements(head, 6);
        System.out.println(res);
    }
}

5-3遞歸基礎與遞歸的宏觀語意

遞歸

  • 本質上,將原來的問題轉化成爲更小的同一問題
  • 舉例:數組求和
    Sum( arr[0…n-1]) = arr[0] + Sum( arr[1…n-1]) ← 更小的同一問題
    Sum( arr[1…n-1]) = arr[1] + Sum( arr[2…n-1]) ← 更小的同一問題

    Sum( arr[n-1…n-1) = arr[n-1] + Sum( [ ] ) ←最基本的問題
public class Sum {

   public static int sum(int[] arr){
       return sum(arr, 0);
   }

   // 計算arr[l...n)這個區間內所有數字的和
   private static int sum(int[] arr, int l){
       if(l == arr.length)
           return 0;
       return arr[l] + sum(arr, l + 1);
   }

   public static void main(String[] args) {

       int[] nums = {1, 2, 3, 4, 5, 6, 7, 8};
       System.out.println(sum(nums));
   }
}

在這裏插入圖片描述

4-10 鏈表的天然遞歸結構性質

鏈表天然的遞歸性

在這裏插入圖片描述

解決鏈表中刪除元素的問題

在這裏插入圖片描述

class Solution5 {

    public ListNode removeElements(ListNode head, int val) {

        if(head == null)
            return head;

        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
    }
}

4-11 遞歸運行的機制:遞歸的微觀解讀

遞歸函數的調用,本質就是函數調用,只是調用的函數是自己而已
遞歸調用是有代價的:函數調用+系統棧空間
在這裏插入圖片描述
在這裏插啊描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章