1. 程式人生 > 其它 >基礎演算法面試題---連結串列

基礎演算法面試題---連結串列

技術標籤:面試基礎演算法題連結串列演算法

前言

一般連結串列的基礎題演算法都很簡單,但卻是常見的面試題,因為連結串列能夠考察面試者的編碼能力,往往很容易想到解題方式,卻寫不出來。

下面總結了幾道常見的初級題,可以反覆練習,提高自己的編碼能力。

先準備兩個物件,一個單鏈表,一個雙鏈表

單鏈表

public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int
val, ListNode next) { this.val = val; this.next = next; } @Override public String toString() { return "ListNode{" + "val=" + val + ", next=" + next + '}'; } }

雙鏈表

public class DoubleListNode
<T> { public T data; public DoubleListNode<T> last; public DoubleListNode<T> next; public DoubleListNode(T data) { this.data = data; } @Override public String toString() { return "DoubleListNode{" + "data="
+ data + ", next=" + next + '}'; } }

1、單鏈表反轉

單鏈表反轉,經典且基礎的連結串列題。

舉例:
原連結串列:1-2-3-4-5
反轉後:5-4-3-2-1

public class Code_01 {
    public static void main(String[] args) {
        ListNode n = new ListNode();
        ListNode head = n;
        for (int i = 1; i <= 5; i++) {
            n.next = new ListNode(i);
            n = n.next;
        }
        System.out.println("原連結串列:" + head);
        ListNode listNode = reverseList(head);
        System.out.println("反轉後:" + listNode);
    }

    private static ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode next;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

在這裡插入圖片描述

2、雙鏈表反轉

public class Code_02 {
    public static void main(String[] args) {
        DoubleListNode n1 = new DoubleListNode(1);
        DoubleListNode n2 = new DoubleListNode(2);
        n1.next = n2;
        n2.last = n1;
        DoubleListNode n3 = new DoubleListNode(3);
        n2.next = n3;
        n3.last = n2;
        System.out.println("原連結串列:" + n1);
        DoubleListNode listNode = reverseDoubleList(n1);
        System.out.println("反轉後:" + listNode);
    }

    private static DoubleListNode reverseDoubleList(DoubleListNode head) {
        DoubleListNode pre = null;
        DoubleListNode next;
        while (head != null) {
            next = head.next;
            head.next = pre;
            head.last = next;
            pre = head;
            head = next;
        }
        return pre;
    }
}

在這裡插入圖片描述

3、刪除連結串列中的某類節點

舉例:
原連結串列:1-2-3-4-5
刪除value=2的節點
結果:1-3-4-5

原連結串列:1-2-3-3-3-4-5
刪除value=3的節點
結果:1-2-4-5

原連結串列:1-1-2-3-4-5
刪除value=1的節點
結果:2-3-4-5

public class Code_03 {
    public static void main(String[] args) {
        ListNode n = new ListNode();
        ListNode head = n;
        for (int i = 1; i <= 5; i++) {
            n.next = new ListNode(i);
            n = n.next;
        }
        System.out.println("原連結串列:" + head);
        ListNode node = deleteNode(head, 3);
        System.out.println("刪除後:" + node);
    }

    private static ListNode deleteNode(ListNode head, int value) {
        //處理head本身就是要刪除的節點
        while (head != null) {
            if (head.val != value) {
                break;
            }
            head = head.next;
        }
        //始終記錄前一個節點,和當前節點的指標,如果當前節點就是要刪除的節點時,則讓前一個節點指向當前節點的下一個節點,即完成了刪除
        ListNode cur = head;
        ListNode pre = null;
        while (cur != null) {
            if (cur.val == value) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}

在這裡插入圖片描述

4、刪除重複元素1

給定一個排序連結串列,刪除所有重複的元素,使得每個元素只出現一次。

舉例:
原連結串列: 1->1->2->3->3
刪除後: 1->2->3

public class Code_05 {
    public static void main(String[] args) {
        Code_05 c = new Code_05();
        ListNode n = new ListNode();
        ListNode head = n;
        for (int i = 1; i <= 5; i++) {
            n.next = new ListNode(i);
            n = n.next;
            if (i % 2 == 0) {
                n.next = new ListNode(i);
                n = n.next;
            }
        }
        System.out.println("原連結串列:" + head);
        System.out.println("刪除後:" + c.deleteDuplicates(head));
    }

    /**
     * 通過不斷移動cur,判斷當前cur的值與cur.next的值是否相等,如果相等,則只改變cur.next,並讓其指向下一個節點,就等於跳過了cur.next的節點
     * 如果不相等,則移動cur節點位置到cur.next上。
     * @param head
     * @return
     */
    public ListNode deleteDuplicates(ListNode head) {
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            if (cur.val != cur.next.val) {
                cur = cur.next;
            } else {
                cur.next = cur.next.next;
            }
        }
        return head;
    }
}

5、刪除重複元素2

給定一個排序連結串列,刪除所有含有重複數字的節點,只保留原始連結串列中沒有重複出現的數字。

舉例:
原連結串列: 1->2->3->3->4->4->5
刪除後: 1->2->5

這是在前一道題目上的延伸。

解法一:

結合前兩題的方式,可以拆分處理,先用第4題的方式刪除重複的數字並記錄下來,再第3題的方式刪除指定數字。

public class Code_06 {

    public static void main(String[] args) {
        Code_06 c = new Code_06();
        ListNode n = new ListNode();
        ListNode head = n;
        for (int i = 1; i <= 5; i++) {
            n.next = new ListNode(i);
            n = n.next;
            if (i % 2 == 0) {
                n.next = new ListNode(i);
                n = n.next;
            }
        }
        System.out.println(head);
        System.out.println(c.deleteDuplicates(head));
    }

    public ListNode deleteDuplicates(ListNode head) {
        ListNode cur = head;
        Set<Integer> dupSet = new HashSet<>();
        while (cur != null && cur.next != null) {
            if (cur.val != cur.next.val) {
                cur = cur.next;
            } else {
                dupSet.add(cur.val);
                cur.next = cur.next.next;
            }
        }
        for (Integer val : dupSet) {
            head = deleteNode(head, val);
        }
        return head;
    }

    private ListNode deleteNode(ListNode head, int val) {
        while (head != null) {
            if (head.val != val) {
                break;
            }
            head = head.next;
        }
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == val) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }

}

在這裡插入圖片描述

當然第一種解法只能當做是編碼的練習,出題者肯定不是希望你用這種方式處理。

解法二:

啞節點+雙指標

public class Code_06_01 {
    public static void main(String[] args) {
        Code_06_01 c = new Code_06_01();
        ListNode n = new ListNode();
        ListNode head = n;
        for (int i = 1; i <= 5; i++) {
            n.next = new ListNode(i);
            n = n.next;
            if (i % 2 == 0) {
                n.next = new ListNode(i);
                n = n.next;
            }
        }
        System.out.println(head);
        System.out.println(c.deleteDuplicates(head));
    }

    /**
     * 啞節點+雙指標
     * <p>
     * 構建一個啞節點,讓其next指向頭位置。
     * 再利用雙指標,n1,n2,初始都指向head位置,如果n1.next.val==n2.next.val,則讓n2向前移動一位,否則n1,n2一起向前移動一位
     *
     * @param head
     * @return
     */
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode n1 = dummy;
        ListNode n2 = head;
        while (n2 != null && n2.next != null) {
            if (n1.next.val != n2.next.val) {
                n1 = n1.next;
            } else {
                //n2一直移動,直到不等於n1為止
                while (n2 != null && n2.next != null && n1.next.val == n2.next.val) {
                    n2 = n2.next;
                }
                n1.next = n2.next;
            }
            n2 = n2.next;
        }
        return dummy.next;
    }
}

在這裡插入圖片描述

6、合併有序連結串列

將兩個升序連結串列合併為一個新的 升序 連結串列並返回。新連結串列是通過拼接給定的兩個連結串列的所有節點組成的。

原連結串列:l1 = [1,2,4],l2 = [1,3,4]
合併後:[1,1,2,3,4,4]

public class Code_04 {

    public static void main(String[] args) {
        ListNode n = new ListNode(1);
        ListNode l1 = n;
        for (int i = 3; i <= 5; i = i + 2) {
            n.next = new ListNode(i);
            n = n.next;
        }
        ListNode n2 = new ListNode(2);
        ListNode l2 = n2;
        for (int i = 4; i <= 6; i = i + 2) {
            n2.next = new ListNode(i);
            n2 = n2.next;
        }
        Code_04 c = new Code_04();

        System.out.println("原連結串列1:" + l1);
        System.out.println("原連結串列2:" + l2);

        System.out.println("合併後:" + c.mergeTwoLists(l1, l2));

    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode mergeNode = new ListNode();
        ListNode pre = mergeNode;
        //比較兩個連結串列當前的值,值小的連結串列就把引用賦給mergeNode,並向後移動一位重新賦值給自己,同時pre指向值小的那個節點
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                pre.next = l1;
                l1 = l1.next;
            } else {
                pre.next = l2;
                l2 = l2.next;
            }
            pre = pre.next;
        }
        pre.next = l1 == null ? l2 : l1;

        return mergeNode.next;
    }
}

在這裡插入圖片描述

7、雙向連結串列實現棧、佇列

佇列:先進先出

棧:先進後出

分別用雙向連結串列實現,從頭進,從頭出,從尾進,從尾出即可模擬出佇列和棧的資料結構。

public class NodeUtils<T> {

    DoubleListNode<T> head;
    DoubleListNode<T> tail;

    /**
     * 從頭進
     * @param data
     */
    public void addHead(T data) {
        DoubleListNode<T> node = new DoubleListNode(data);
        if (head == null) {
            head = node;
            tail = node;
        } else {
            node.next = head;
            head.last = node;
            head = node;
        }
    }

    /**
     * 從尾進
     * @param data
     */
    public void addTail(T data) {
        DoubleListNode<T> node = new DoubleListNode(data);
        if (head == null) {
            head = node;
        } else {
            tail.next = node;
            node.last = tail;
        }
        tail = node;
    }

    /**
     * 從頭出
     * @return
     */
    public T popHead() {
        if (head == null) {
            return null;
        }
        DoubleListNode<T> h = head;
        if (head == tail) {
            head = null;
            tail = null;
        } else {
            head = head.next;
            head.last = null;
        }
        return h.data;
    }

    /**
     * 從尾出
     * @return
     */
    public T popTail() {
        if (tail == null) {
            return null;
        }
        DoubleListNode<T> t = tail;
        if (head == tail) {
            head = null;
            tail = null;
        } else {
            tail = tail.last;
            tail.next = null;
        }
        return t.data;

    }

}

佇列

/**
 * 佇列(先進先出):從連結串列頭進,從連結串列尾出
 * @param <T>
 */
public class ListNodeQueue<T> {

    NodeUtils<T> nodeUtils = new NodeUtils();

    public void push(T data) {
        nodeUtils.addHead(data);
    }

    public T pop() {
        return nodeUtils.popTail();
    }

}

/**
 * 佇列(先進先出):從連結串列頭進,從連結串列尾出
 *
 * @param <T>
 */
public class ListNodeQueue<T> {

    NodeUtils<T> nodeUtils = new NodeUtils();

    public void push(T data) {
        nodeUtils.addHead(data);
    }

    public T pop() {
        return nodeUtils.popTail();
    }

}

驗證

public class Code_07 {
    public static void main(String[] args) {
        ListNodeStack stack = new ListNodeStack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println("棧:壓進去1,2,3");
        System.out.println("彈出" + stack.pop() + "," + stack.pop() + "," + stack.pop());

        ListNodeQueue queue = new ListNodeQueue();
        queue.push(1);
        queue.push(2);
        queue.push(3);
        System.out.println("佇列:壓進去1,2,3");
        System.out.println("彈出" + queue.pop() + "," + queue.pop() + "," + queue.pop());
    }
}

在這裡插入圖片描述