Skip to content

Commit 4ac2f93

Browse files
committed
Linked List: Find Middle of the Linked List in Java #361
1 parent c0f36a1 commit 4ac2f93

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Linked List/MiddleOfLinkedList.java

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/* QUESTION and SAMPLE I/O
2+
3+
Given the head of a singly linked list, return the middle node of the linked list.
4+
If there are two middle nodes, return the second middle node.
5+
6+
Sample Input = [1,2,3,4,5]
7+
Sample Output = 3
8+
9+
APPROACH and EXPLANATION
10+
11+
This program is done using two pointers: slow pointer and fast pointer.
12+
* Both pointer starts from the head node.
13+
* Slow pointer moves one step at a time.
14+
* Fast pointer moves two steps at a time.
15+
* As the fast pointer reaches the end, slow pointer will be at the middle of the linked list.
16+
* Accessing the slow pointer's value for 'val' will give you the value for the middle element of linked list.
17+
18+
19+
Time Complexity: O(n)
20+
Space Complexity: O(1)
21+
22+
*/
23+
24+
25+
/**
26+
* Definition for singly-linked list.
27+
* public class ListNode {
28+
* int val;
29+
* ListNode next;
30+
* ListNode() {}
31+
* ListNode(int val) { this.val = val; }
32+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
33+
* }
34+
*/
35+
36+
class Solution {
37+
public ListNode middleNode(ListNode head) {
38+
ListNode slow_pointer = head; //initialize slow pointer
39+
ListNode fast_pointer = head; //initialize fast pointer
40+
while(fast_pointer!=null && fast_pointer.next!=null){
41+
slow_pointer = slow_pointer.next; //moves to next node
42+
fast_pointer = fast_pointer.next.next; //moves two nodes forward
43+
}
44+
return slow_pointer;
45+
}
46+
}

0 commit comments

Comments
 (0)