write once,run anywhere
  • Home
  • Tags
  • Archives

LeetCode [203] Remove Linked List Elements

Contents

  • Questions
  • Coding
    • python

Questions¶

Difficulty: Easy

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

Coding¶

python¶

# -*- coding: utf-8 -*-
# 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 head
        while head.val == val:
            head = head.next
            if head == None:
                return head
        p = head
        while p.next != None:
            if p.next.val == val:
                p.next = p.next.next
            else:
                p = p.next
        if p.val == val:
            p = p.next
        return head

Related Posts

  • LeetCode [1] Two Sum
  • LeetCode [2] Add Two Numbers
  • LeetCode [58] Length of Last Word
  • LeetCode [190] Reverse Bits
  • LeetCode [151] Reverse Words in a String

  • « LeetCode [151] Reverse Words in a String
  • LeetCode [206] Reverse Linked List »

Published

8月 21, 2016

Last Updated

8月 21, 2016

Category

Linux

Tags

  • LeetCode 13

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor