From ddc8e2de604813772abe857bd7e7906ef2837fa0 Mon Sep 17 00:00:00 2001 From: mengyi Date: Sun, 9 Jun 2024 21:30:32 -0400 Subject: [PATCH] update project 203 java version solution --- problems/0203.移除链表元素.md | 54 ++++++++++++++++------------- 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index efcc6414..64124fbb 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -224,9 +224,10 @@ struct ListNode* removeElements(struct ListNode* head, int val){ ### Java: +用原来的链表操作: ```java /** - * 添加虚节点方式 + * 方法1 * 时间复杂度 O(n) * 空间复杂度 O(1) * @param head @@ -234,25 +235,22 @@ struct ListNode* removeElements(struct ListNode* head, int val){ * @return */ public ListNode removeElements(ListNode head, int val) { - if (head == null) { - return head; + while(head!=null && head.val==val) { + head = head.next; } - // 因为删除可能涉及到头节点,所以设置dummy节点,统一操作 - ListNode dummy = new ListNode(-1, head); - ListNode pre = dummy; - ListNode cur = head; - while (cur != null) { - if (cur.val == val) { - pre.next = cur.next; + ListNode curr = head; + while(curr!=null && curr.next !=null) { + if(curr.next.val == val){ + curr.next = curr.next.next; } else { - pre = cur; + curr = curr.next; } - cur = cur.next; } - return dummy.next; + return head; } + /** - * 不添加虚拟节点方式 + * 方法1 * 时间复杂度 O(n) * 空间复杂度 O(1) * @param head @@ -280,8 +278,13 @@ public ListNode removeElements(ListNode head, int val) { } return head; } + +``` + +设置一个虚拟头结点: + +```java /** - * 不添加虚拟节点and pre Node方式 * 时间复杂度 O(n) * 空间复杂度 O(1) * @param head @@ -289,18 +292,21 @@ public ListNode removeElements(ListNode head, int val) { * @return */ public ListNode removeElements(ListNode head, int val) { - while(head!=null && head.val==val){ - head = head.next; - } - ListNode curr = head; - while(curr!=null){ - while(curr.next!=null && curr.next.val == val){ - curr.next = curr.next.next; + // 设置一个虚拟的头结点 + ListNode dummy = new ListNode(); + dummy.next = head; + + ListNode cur = dummy; + while (cur.next != null) { + if (cur.next.val == val) { + cur.next = cur.next.next; + } else { + cur = cur.next; } - curr = curr.next; } - return head; + return dummy.next; } + ``` ### Python: