Given a non-empty, singly linked list with head node
If there are two middle nodes, return the second middle node.
Example 1:
Example 2:
Note:
- The number of nodes in the given list will be between
1 and100 .
Solution
To get the middle element we need to require length of the LinkedList, Iterate over and calculate the length of the LinkedList. Divide it and iterate again till we reach to the middle element.
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode middleNode(ListNode head) { int l=0,mid=0,tempMid=1; ListNode node=head; while(node!=null){ l++; node=node.next; } mid=l/2; mid++; node=head; while(tempMid<mid){ node=node.next; tempMid++; } return node; } } |
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.