leetcode-----Remove Linked List Elements

标题: Remove Linked List Elements
通过率: 30.5%
难度: 简单

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

本题就是一个很普通的链表节点删除,需要注意的是开始时在原有的链表的头结点前加一个无关的头,代码如下:

 1 # Definition for singly-linked list.

 2 # class ListNode:

 3 #     def __init__(self, x):

 4 #         self.val = x

 5 #         self.next = None

 6 

 7 class Solution:

 8     # @param {ListNode} head

 9     # @param {integer} val

10     # @return {ListNode}

11     def removeElements(self, head, val):

12         if head==None:return head

13         pre=ListNode(-1)

14         pre.next=head

15         res,first,second=pre,pre,head

16         while second!= None:

17             if second.val==val:

18                 first.next=second.next

19                 second=second.next

20             else:first,second=second,second.next

21         return pre.next

 

你可能感兴趣的:(LeetCode)