Skip to content

Commit f646c54

Browse files
authored
Merge pull request #1130 from akshaymagar2003/main
Middle of Linked List in java
2 parents ffcaefc + e1b1072 commit f646c54

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Linked List/FindMiddleLinkedList.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
In this code, the ListNode class represents a node in the linked list, with an integer value val and a reference to the next node next. The FindMiddleLinkedList class has a findMiddle method that takes a ListNode as its input and returns the middle node of the linked list using the fast and slow pointers algorithm.
3+
4+
*/
5+
class ListNode {
6+
int val;
7+
ListNode next;
8+
9+
ListNode(int val) {
10+
this.val = val;
11+
this.next = null;
12+
}
13+
}
14+
15+
class FindMiddleLinkedList {
16+
public ListNode findMiddle(ListNode head) {
17+
// Create two pointers, slow and fast, both initially pointing to the head of the linked list.
18+
ListNode slow = head;
19+
ListNode fast = head;
20+
21+
// Move the slow pointer one step at a time and the fast pointer two steps at a time, until the fast pointer reaches the end of the list.
22+
while (fast != null && fast.next != null) {
23+
slow = slow.next;
24+
fast = fast.next.next;
25+
}
26+
27+
// When the fast pointer reaches the end of the list, the slow pointer will be pointing to the middle of the list.
28+
return slow;
29+
}
30+
31+
public static void main(String[] args) {
32+
// Create a sample linked list
33+
ListNode head = new ListNode(1);
34+
head.next = new ListNode(2);
35+
head.next.next = new ListNode(3);
36+
head.next.next.next = new ListNode(4);
37+
head.next.next.next.next = new ListNode(5);
38+
39+
// Create an instance of the FindMiddleLinkedList class
40+
FindMiddleLinkedList f = new FindMiddleLinkedList();
41+
42+
// Call the findMiddle method to get the middle node of the linked list
43+
ListNode middleNode = f.findMiddle(head);
44+
45+
// Print the value of the middle node
46+
System.out.println("The middle node has value: " + middleNode.val);
47+
}
48+
}

0 commit comments

Comments
 (0)