Skip to content

Commit c564820

Browse files
Merge pull request #2579 from MengyiG/mengyi203
Update problem 203 Java solution
2 parents 2de818a + ddc8e2d commit c564820

File tree

1 file changed

+30
-24
lines changed

1 file changed

+30
-24
lines changed

problems/0203.移除链表元素.md

Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -224,35 +224,33 @@ struct ListNode* removeElements(struct ListNode* head, int val){
224224
225225
### Java:
226226
227+
用原来的链表操作:
227228
```java
228229
/**
229-
* 添加虚节点方式
230+
* 方法1
230231
* 时间复杂度 O(n)
231232
* 空间复杂度 O(1)
232233
* @param head
233234
* @param val
234235
* @return
235236
*/
236237
public ListNode removeElements(ListNode head, int val) {
237-
if (head == null) {
238-
return head;
238+
while(head!=null && head.val==val) {
239+
head = head.next;
239240
}
240-
// 因为删除可能涉及到头节点,所以设置dummy节点,统一操作
241-
ListNode dummy = new ListNode(-1, head);
242-
ListNode pre = dummy;
243-
ListNode cur = head;
244-
while (cur != null) {
245-
if (cur.val == val) {
246-
pre.next = cur.next;
241+
ListNode curr = head;
242+
while(curr!=null && curr.next !=null) {
243+
if(curr.next.val == val){
244+
curr.next = curr.next.next;
247245
} else {
248-
pre = cur;
246+
curr = curr.next;
249247
}
250-
cur = cur.next;
251248
}
252-
return dummy.next;
249+
return head;
253250
}
251+
254252
/**
255-
* 不添加虚拟节点方式
253+
* 方法1
256254
* 时间复杂度 O(n)
257255
* 空间复杂度 O(1)
258256
* @param head
@@ -280,27 +278,35 @@ public ListNode removeElements(ListNode head, int val) {
280278
}
281279
return head;
282280
}
281+
282+
```
283+
284+
设置一个虚拟头结点:
285+
286+
```java
283287
/**
284-
* 不添加虚拟节点and pre Node方式
285288
* 时间复杂度 O(n)
286289
* 空间复杂度 O(1)
287290
* @param head
288291
* @param val
289292
* @return
290293
*/
291294
public ListNode removeElements(ListNode head, int val) {
292-
while(head!=null && head.val==val){
293-
head = head.next;
294-
}
295-
ListNode curr = head;
296-
while(curr!=null){
297-
while(curr.next!=null && curr.next.val == val){
298-
curr.next = curr.next.next;
295+
// 设置一个虚拟的头结点
296+
ListNode dummy = new ListNode();
297+
dummy.next = head;
298+
299+
ListNode cur = dummy;
300+
while (cur.next != null) {
301+
if (cur.next.val == val) {
302+
cur.next = cur.next.next;
303+
} else {
304+
cur = cur.next;
299305
}
300-
curr = curr.next;
301306
}
302-
return head;
307+
return dummy.next;
303308
}
309+
304310
```
305311

306312
### Python:

0 commit comments

Comments
 (0)