Leetcode: Remove Linked List Elements

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

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Golang
// Basic Ideas
// Complexity: Time O(n), Space O(1)
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

/**
 * @param head: a ListNode
 * @param val: An integer
 * @return: a ListNode
 */
func removeElements (head *ListNode, val int) *ListNode {
    dummyNode := &ListNode{0, head}
    p := dummyNode
    for p.Next != nil {
        if p.Next.Val == val {
            p.Next = p.Next.Next
        } else {
            p = p.Next
        }
    }
    return dummyNode.Next
}

  • Python
## Blog link: https://code.dennyzhang.com/remove-linked-list-elements
## Basic Ideas: The head might be removed, thus we need a dummy node
## Complexity: Time O(n), Space O(1)
# 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
        """
        dummyNode = ListNode(None, head)
        p = dummyNode
        while p.next:
            if p.next.val == val:
                p.next = p.next.next
            else:
                p = p.next
        return dummyNode.next
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.