Skip to content

82. Remove Duplicates from Sorted List II

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

js
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function(head) {
  var dummy = new ListNode()
  dummy.next = head
  var current = dummy

  while (current.next && current.next.next) {
    if (current.next.val === current.next.next.val) {
      let val = current.next.val
      while (current.next && current.next.val === val) {
        current.next = current.next.next
      }
    } else {
      current = current.next
    }
  }

  return dummy.next
}
py
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution(object):

    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        current = dummy = ListNode(None)
        dummy.next = head

        while current.next and current.next.next:
            if current.next.val == current.next.next.val:
                val = current.next.val
                while current.next and current.next.val == val:
                    current.next = current.next.next
            else:
                current = current.next

        return dummy.next