LeetCode 203. Remove Linked List Elements

题目

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5

分析

删除链表中等于目标值的节点

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head is None:
return None
cur = dummy = ListNode(-1)
cur.next = head
while cur != None and cur.next != None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy.next

点评

首先申请一个头结点,和两个头指针,一个作为游标指针,一个作为锚指针,然后将链表串入头结点之后。接着遍历链表直到游标指针为空,每次遍历判断当前节点的后继节点值和目标值大小,如果相等,则更新后继节点为后继节点的后继节点,否则更新游标为当前节点的后继节点