Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Delete Middle Node

Easy
0/40
Average time to solve is 15m
profile
Contributed by
70 upvotes
Asked in companies
GrowwPaytm (One97 Communications Limited)Adobe

Problem statement

Given a singly linked list of 'N' nodes. Your task is to delete the middle node of this list and return the head of the modified list.


However, if the list has an even number of nodes, we delete the second middle node


Example:
If given linked list is 1->2->3->4 then it should be modified to 1->2->4.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line contains an integer 'N', the size of the linked list.
The second line contains 'N' space-separated integers.
Output Format :
The output contains all the nodes of linked list except the middle node. If the list is empty, '-1' will be printed.
Note :
You are not required to print the output, it has already been taken care of. Just implement the function.
Follow up :
Try to solve this problem in O(N) time complexity and O(1) space complexity.

Can you solve it in only one traversal of the Linked List?
Sample Input 1 :
5
1 2 3 4 5
Sample Output 1 :
1 2 4 5 
Explanation to Sample Input 1 :
We can clearly see that there are 5 nodes in the linked list therefore the middle node is the node with value '3'.
Sample Input 2 :
1
2
Sample Output 2 :
-1
Explanation to Sample Input 1 :
We can clearly see that there is only one node in the linked list.
Therefore, after deleting that one node, the linked list becomes empty, resulting in an output of -1.
Constraints :
1 <= N <= 10^3
0 <= data <= 10^3 

Where 'N' is the length of the linked list.

Time Limit: 1 sec
Full screen
Console