程式碼隨想錄演算法訓練營第三天| 203. 移除連結串列元素 707.設計連結串列 206.反轉連結串列

jeasonGo發表於2024-03-08

203. 移除連結串列元素
https://leetcode.cn/problems/remove-linked-list-elements/description/

public ListNode removeElements(ListNode head, int val) {
        if (head == null) return head;
        ListNode wHead = new ListNode(Integer.MAX_VALUE,head);
        ListNode p = head;
        ListNode pre = wHead;
        while (p != null){
            if (p.val == val){
                pre.next = p.next;
                p = pre.next;
            }else {
                pre = pre.next;
                p = p.next;
            }
        }
        return wHead.next;
    }

總結:這破題,出的就有問題,這就是不帶頭結點的連結串列,非得說是帶頭節點的,哪有帶頭節點的連結串列頭結點還有值的啊,破題浪費我半個多小時
707.設計連結串列
https://leetcode.cn/problems/design-linked-list/description/

class MyLinkedList {
    int size;

    ListNode head;

    public MyLinkedList(){
        size = 0;
        head = new ListNode(Integer.MAX_VALUE);
    }
    public int get(int index){
        if (index < 0 || index >= size){
            return -1;
        }
        ListNode p = head;
        for (int i = 0; i <= index; i++) {
            p = p.next;
        }
        return p.val;
    }
    public void  addAtHead(int val){
        addAtIndex(0,val);
    }
    public void addAtTail(int val){
        addAtIndex(size,val);
    }
    public void addAtIndex(int index,int val){
        if (index > size || index < 0) return;
        ListNode p = head;
        for (int i = 0; i < index; i++) {
            p = p.next;
        }
        if (index == size){
            ListNode newNode = new ListNode(val);
            p.next = newNode;
            size++;
        }else {
            ListNode newNode = new ListNode(val,p.next);
            p.next = newNode;
            size++;
        }
    }
    public void deleteAtIndex(int index){
        if (index < 0 || index >= size) return;
        ListNode p = head;
        for (int i = 0; i < index; i++) {
            p = p.next;
        }
        p.next = p.next.next;
        size--;
    }
    class ListNode {
    int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
}

總結:細緻一點就好了,不要急
206.反轉連結串列
https://leetcode.cn/problems/reverse-linked-list/description/

//頭插法
public static ListNode reverseList(ListNode head) {
        ListNode newHead = new ListNode();
        while (head != null){
            ListNode l = head.next;
            head.next = newHead.next;
            newHead.next = head;
            head = l;
        }
        return newHead.next;
    }
//三指標法
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode p = head;
        ListNode temp = null;
        while (p != null){
            temp = p.next;
            p.next = pre;
            pre = p;
            p = temp;
        }
        return pre;
    }

總結:注意辨析題目到底是不是個有頭結點的連結串列,很煩,兩種方法,頭插法,三指標(邏輯上透過改變指標走向去實現翻轉)

相關文章