Skip to content

Commit 1025c60

Browse files
middle node ll java
1 parent d7e5a5f commit 1025c60

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Java/middle-of-the-linked-list.java

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode middleNode(ListNode head) {
13+
ListNode currentNode = head;
14+
15+
ListNode slowPtr = head;
16+
ListNode fastPtr = head;
17+
18+
while(fastPtr != null && fastPtr.next != null){
19+
slowPtr = slowPtr.next; // slow pointer will move 1 node at a time
20+
fastPtr = fastPtr.next.next; // fast pointer will move 2 nodes at a time
21+
}
22+
23+
// at end slow pointer will be pointing to middle node
24+
return slowPtr;
25+
}
26+
}

0 commit comments

Comments
 (0)