[Question]: Given a doubly linked list and a key x. The problem is to delete all occurrences of the given key x from the doubly linked list.
#Approach: we declare two variable prevNode and nxtNode and in a loop if we finds the data value of linklist node is equals to k just break link to the node.
func deleteOccuranceInLinkedList(_ k: Int, _ list: DoublyLinkedListNode<Int>?) -> DoublyLinkedListNode<Int>? {
var tempCopy = list
while tempCopy != nil {
var prevNode = tempCopy?.previous
var nxtNode = tempCopy?.next
if tempCopy?.item == k {
prevNode?.next = nxtNode
nxtNode?.previous = prevNode
}
tempCopy = tempCopy?.next
}
return tempCopy
}
var occuranceLinkedList = DoublyLinkedList<Int>()
occuranceLinkedList = [1,2,3,2,1,4,5]
deleteOccuranceInLinkedList(2, occuranceLinkedList.head)
//print(" after deleting k linked list is", occuranceLinkedList)// 1,3,1,4,5