203. Remove Linked List Elements(python)

来源:互联网 发布:巡检器如何下载数据 编辑:程序博客网 时间:2024/04/29 19:54

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
Runtime: 156 ms
总结:建立虚表头,比较p.next,如果p.next==6,则p不变,p.next变,否则p=p.next
类似于删除重复节点,删除的元素在p.next,要保证p不动

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def removeElements(self, head, val):        dummy=ListNode(0)        dummy.next=head        p=dummy        while p.next:            if p.next.val==val:                p.next=p.next.next            else:                p=p.next        return dummy.next 
0 0
原创粉丝点击