203. 移除链表元素

题目链接:https://leetcode-cn.com/problems/remove-linked-list-elements/

执行用时:52 ms, 在所有 Swift 提交中击败了97.20%的用户
内存消耗:15.3 MB, 在所有 Swift 提交中击败了53.20%的用户

解题思路

两根指针效率和一根指针在这里差距不大,也挺好理解

一根指针的情况就是只有pre,判断pre.next的值,如果要删除,就使pre.next 指向删除节点的next也就是pre.next.next
两根指针的情况分析:
1,首先设置虚拟头节点
2,慢指针指向头节点,处于前一个位置
3,cur指针指向真实的头节点
4,当cur的节点值和传入的val相等时,向后移动cur
5,使前一个指针pre指向更新后的cur
6,如果不想等则pre 和 cur一起向后移动

两根指针代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
var dummy = ListNode(0,head)
var pre = dummy
var cur = head
while cur != nil {
if cur?.val == val {
cur = cur?.next
pre.next = cur
}else{
cur = cur?.next
pre = pre.next!
}
}
return dummy.next
}
}

执行用时:48 ms, 在所有 Swift 提交中击败了96.89%的用户
内存消耗:15.4 MB, 在所有 Swift 提交中击败了53.42%的用户

一根指针代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
var dummy = ListNode(0, head)
var pre = dummy
while let cur = pre.next {
if cur.val == val {
pre.next = cur.next
}else{
pre = cur
}
}
return dummy.next
}
}


203. 移除链表元素
https://pisces34.github.io/2021/08/01/leetcode/203/
发布于
2021年8月1日
许可协议