Skip to content

83. Remove Duplicates from Sorted List

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

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

  var prev = head
  var current = head.next

  while (current) {
    if (current.val !== prev.val) {
      prev = prev.next = current
    }
    current = current.next
  }

  prev.next = null

  return head
}
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
        """
        if not head:
            return head

        prev, current = head, head.next
        while current:
            if current.val != prev.val:
                prev.next = current
                prev = prev.next
            current = current.next
        prev.next = None

        return head