Skip to content

Commit c9604bd

Browse files
committed
1 parent c507286 commit c9604bd

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Linked List/linked_list_middle.go

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node.
3+
*
4+
* Example #1:
5+
* Input: head = [1,2,3,4,5]
6+
* Output: [3,4,5]
7+
* Explanation: The middle node of the list is node 3.
8+
*
9+
* Example #2:
10+
* Input: head = [1,2,3,4,5,6]
11+
* Output: [4,5,6]
12+
* Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
13+
*
14+
* Constraints:
15+
* The number of nodes in the list is in the range [1, 100].
16+
* 1 <= Node.val <= 100
17+
*
18+
* Definition for singly-linked list.
19+
* type ListNode struct {
20+
* Val int
21+
* Next *ListNode
22+
* }
23+
*
24+
* Solution: to find the middle of a linked list, we can use two pointers ("slow" and "fast"). They should both start at head.
25+
* While traversing the list, we move the slow pointer one node at a time and the fast pointer two nodes at a time.
26+
* When the fast pointer reaches the end of the linked list, the slow pointer will be pointing to the middle node.
27+
*
28+
* Time complexity: O(n), space complexity: O(n)
29+
*/
30+
func middleNode(head *ListNode) *ListNode {
31+
slow, fast := head, head
32+
33+
for (fast != nil && fast.Next != nil) {
34+
slow = slow.Next
35+
fast = fast.Next.Next
36+
}
37+
38+
return slow
39+
}

0 commit comments

Comments
 (0)