Delete Middle node from Single Link List

[Question]: You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.

The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.

func deleteMiddle(_ head: ListNode?) -> ListNode? {
     if head?.next == nil {
         return nil
     }
     var slowPointer = head // 1X time mover
     var fastPointer = head// 2X mover
     var prevNode: ListNode?// This is middle - 1 Node
     while fastPointer?.next != nil {
         fastPointer = fastPointer?.next?.next
         prevNode = slowPointer
         slowPointer = slowPointer?.next
     }
     prevNode?.next = slowPointer?.next// middle Node - 1 next's is middle + 1 node
     return head
 }

var aLinkList = ListNode(1, ListNode(2, ListNode(3)))
aLinkList = deleteMiddle(aLinkList)!
print("After Deleting Link list will look like--", aLinkList) //  1 -> 3 

Leave a Comment

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