From b19af65b79a1bb4fd64dc7523a5fa60867b29b0e Mon Sep 17 00:00:00 2001 From: weikunkun Date: Wed, 12 May 2021 21:07:20 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00203.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 58 ++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index e6667091..9fca1ee0 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -138,7 +138,63 @@ public: Java: - +```java +/** + * 添加虚节点方式 + * 时间复杂度 O(n) + * 空间复杂度 O(1) + * @param head + * @param val + * @return + */ +public ListNode removeElements(ListNode head, int val) { + if (head == null) { + return head; + } + // 因为删除可能涉及到头节点,所以设置dummy节点,统一操作 + ListNode dummy = new ListNode(-1, head); + ListNode pre = dummy; + ListNode cur = head; + while (cur != null) { + if (cur.val == val) { + pre.next = cur.next; + } else { + pre = cur; + } + cur = cur.next; + } + return dummy.next; +} +/** + * 不添加虚拟节点方式 + * 时间复杂度 O(n) + * 空间复杂度 O(1) + * @param head + * @param val + * @return + */ +public ListNode removeElements(ListNode head, int val) { + while (head != null && head.val == val) { + head = head.next; + } + // 已经为null,提前退出 + if (head == null) { + return head; + } + // 已确定当前head.val != val + ListNode pre = head; + ListNode cur = head.next; + while (cur != null) { + if (cur.val == val) { + pre.next = cur.next; + } else { + pre = cur; + } + cur = cur.next; + } + return head; +} +``` Python: