Problem of the day
Given a singly linked list of 'N' nodes. The objective is to determine the middle node of a singly linked list. However, if the list has an even number of nodes, we return the second middle node.
Note:1. If the list is empty, the function immediately returns None because there is no middle node to find.
2. If the list has only one node, then the only node in the list is trivially the middle node, and the function returns that node.
The first line contains an integer 'N', the size of the linked list.
The second line contains 'N' space-separated integers.
The output contains all the integers from the middle node.
You do not need to print anything, it has already been taken care of. Just implement the given function.
5
1 2 3 4 5
3 4 5
We can clearly see that there are 5 elements in the linked list therefore the middle node is the node with value '3'.
6
1 2 3 4 5 6
4 5 6
We can clearly see that there are 6 elements in the linked list and the middle nodes are nodes with values 3 and 4 hence we return a second middle node having value '4'.
1 <= 'N' <= 10^4
0 <= 'data' <= 10^3
Where 'N' is the length of the linked list.
Time Limit: 1 sec
Try to find the number of elements in the given Linked List.
We can take the Following Approach:
O(N), Where ‘N’ denotes the number of elements in the Linked List
Since we need to traverse the linked list twice first to find the number of elements and secondly again to find the middle node the overall complexity is the order of ‘N’.
O(1),
We are using constant space.