第三天 | 移除链表元素 | 设计链表 | 反转链表

2,417 阅读2分钟

移除链表元素

随想录的文章链接

programmercarl.com/0203.%E7%A7…

看完代码随想录之后的想法

虚拟头节点可以让逻辑变的更简单。

自己实现过程中遇到哪些困难

没碰到困难。

今日收获,记录一下自己的学习时长

文章5分钟,写代码10分钟。

public static ListNode removeElements(ListNode head, int val) {
    ListNode dummyNode = new ListNode(-1, head);
    ListNode pre = dummyNode;
    ListNode cur = dummyNode.next;
    while (cur != null) {
        if (cur.val == val) {
            pre.next = cur.next;
            cur.next = null;
        } else {
            pre = cur;
        }
        cur = pre.next;
    }
    return dummyNode.next;
}

设计链表

随想录的文章链接

programmercarl.com/0707.%E8%AE…

看完代码随想录之后的想法

自己实现没有用虚拟头节点,逻辑上要复杂一点,也更容易出错。尤其是双向链表。

自己实现过程中遇到哪些困难

由于没有用虚拟头节点,临界条件判断多次出错,相同的功能在开始未抽象,浪费了不少时间。

今日收获,记录一下自己的学习时长

文章10分钟,写代码30分钟。双向链表也用了30分钟,但代码不够简洁,此处就不贴了。随想录来的代码更漂亮。

class MyLinkedList {
    private ListNode head;
    private int length;

    public MyLinkedList() {
        head = null;
        length = 0;
    }

    private ListNode getIndexNode(int i) {
        if (i < 0 || i >= length) {
            return null;
        }

        ListNode cur = head;
        for (int j = 0; j < i; j++) {
            cur = cur.next;
        }
        return cur;
    }

    public int get(int index) {
        ListNode cur = getIndexNode(index);
        return cur == null ? -1 : cur.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    public void addAtTail(int val) {
        addAtIndex(length, val);
    }

    public void addAtIndex(int index, int val) {
        if (index > length) {
            return;
        }

        length++;
        ListNode pre = getIndexNode(index - 1);
        if (pre == null) {
            head = new ListNode(val, head);
        } else {
            pre.next = new ListNode(val, pre.next);
        }
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= length) {
            return;
        }

        length--;
        ListNode pre = getIndexNode(index - 1);
        if (pre == null) {
            head = head.next;
        } else {
            pre.next = pre.next.next;
        }
    }
}

链表反转

随想录的文章链接

programmercarl.com/0206.%E7%BF…

看完代码随想录之后的想法

随想录的递归版本和我的递归版本不同,大家可以比较一下。

自己实现过程中遇到哪些困难

没碰到困难。

今日收获,记录一下自己的学习时长

文章5分钟,写代码10分钟。

public static ListNode reverseList(ListNode head) {
    if (head == null) {
        return null;
    }

    ListNode cur = head;
    ListNode pre = null;
    while (cur != null) {
        ListNode next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    return pre;
}

// 递归版本
public static ListNode reverseList2(ListNode head) {
    if (head.next == null) {
        return head;
    }

    ListNode next = head.next;
    ListNode newHead = reverseList2(next);
    next.next = head;
    head.next = null;
    return newHead;
}