How to remove duplicates from a sorted doubly linked list

[Question]: Given a sorted doubly linked list head. Remove duplicate nodes from the given list.

#Approach:
Step 1: Compare current node item with next node item
Step 2: If two items same move next pointer to next’s next
Step 3: If current Node & next Node doesn’t match use node = next

func removeDupsFromSortedDLL( _ head: DoublyLinkedListNode<Int>?) -> DoublyLinkedListNode<Int>? {    
    var node = head
    while let next = node?.next {
        if  node!.item == next.item {
            let nxtItem = next.next
            node!.next = nxtItem
            nxtItem?.previous = node
        } else {
            node = next
        }
    }
    return head
}

var sortedDLL =  DoublyLinkedList<Int>()
sortedDLL = [1,2,2,2,3,3,4,9]
let sortedDLLOutput = removeDupsFromSortedDLL(sortedDLL.head)
print("sorted DLL is--- ",sortedDLLOutput) // (1 <- -> 2 <- -> 3 <- -> 4 <- -> 9)

Leave a Comment

Your email address will not be published. Required fields are marked *