203.移除链表元素

leetcode链接:
https://leetcode.cn/problems/remove-linked-list-elements/solution/203yi-chu-lian-biao-yuan-su-by-lewis-dxstabdzew/

方案一

暴力求解

参考: https://leetcode.cn/problems/remove-linked-list-elements/solution/yi-chu-lian-biao-yuan-su-by-leetcode-sol-654m/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public ListNode removeElements(ListNode head, int val) {

while(head != null && head.val == val) {
head = head.next;
}
if (head == null) {
return head;
}

ListNode flag = head;

while(head.next != null) {
if (head.next.val == val) {
head.next = head.next.next;
} else {
head = head.next;
}
}

return flag;
}
}

Accepted

  • 66/66 cases passed (0 ms)
  • Your runtime beats 100 % of java submissions
  • Your memory usage beats 21 % of java submissions (44 MB)

分析

时间复杂度:
O( n )

空间复杂度:
O( 1 )

方案二

迭代

参考: https://leetcode.cn/problems/remove-linked-list-elements/solution/203yi-chu-lian-biao-yuan-su-by-lewis-dxstabdzew/ 中的方法三。

1
2
3
4
5
6
7
8
9
if (head == null) {
return null;
}
head.next = removeElements(head.next, val);
if (head.val == val) {
return head.next;
} else{
return head;
}

Accepted

  • 66/66 cases passed (0 ms)
  • Your runtime beats 100 % of java submissions
  • Your memory usage beats 11.67 % of java submissions (44.2 MB)

203.移除链表元素
http://yuanql.top/2023/06/04/02_leetcode/203.移除链表元素/
作者
Qingli Yuan
发布于
2023年6月4日
许可协议