1. 程式人生 > >LeetCode203:Remove Linked List Elements

LeetCode203:Remove Linked List Elements

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

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

LeetCode:連結

這題的思路很巧妙,可以和LeetCode83:Remove Duplicates from Sorted List做法一樣。

和val不相等的地方不用動,只需要修改和val相等的地方。

# 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
        """
        dummy = ListNode(-1)
        dummy.next = head
        pcur = dummy

        while pcur.next:
            '''如果和val相等 就修改連線'''
            if pcur.next.val == val:
                pcur.next = pcur.next.next
            else:
                pcur = pcur.next
        return dummy.next