algorithm to find middle element of linked list @ O(n/2) order
MAY 10, 2013 LEAVE A COMMENT
Since every node in a linked list has the reference to its next node, we can achieve this solution by taking two pointers.
For every increment in one pointer, increment the second pointer twice, in this way by the time second pointer reaches the end of the linked list, first pointer should reach the middle element of the linked list.
1
2
3
4
5
6
7
8
| public void traverse(Node node) { tmp = node; while (tmp != null && tmp.next != null ) { node = node.next; tmp = tmp.next.next; } System.out.println( "Middle element of the list is: " + node.value); } |
Note: With this logic, in any linked list we can find 1/2th element (with above logic) OR 1/3rd element (by replacing the code ‘tmp = tmp.next.next;’ to tmp = tmp.next.next.next;) OR 1/4th element (by replacing the code ‘tmp = tmp.next.next;’ to tmp = tmp.next.next.next.next;), so on
------------------------------------------------------------------------------------------------------------------------------------------------------------
My comments: can we just use LinkedList.size() divided by 2 and have a for loop to go next till "size()/2" is reached?
No comments:
Post a Comment