Skip to content

Commit 6f5183d

Browse files
Create 876. Middle of the Linked List.md
1 parent ce0b800 commit 6f5183d

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
## Problem
2+
3+
https://leetcode.com/problems/middle-of-the-linked-list/
4+
5+
## Problem Description
6+
7+
Given the head of a singly linked list, return the middle node of the linked list.
8+
9+
If there are two middle nodes, return the second middle node.
10+
11+
**Example 1:**
12+
13+
**Input:** head = [1,2,3,4,5]
14+
15+
**Output:** [3,4,5]
16+
17+
**Explanation:** The middle node of the list is node 3.
18+
<br>
19+
20+
**Example 2:**
21+
22+
**Input:** head = [1,2,3,4,5,6]
23+
24+
**Output:** [4,5,6]
25+
26+
**Explanation:** Since the list has two middle nodes with values 3 and 4, we return the second one.
27+
28+
29+
## Code
30+
31+
- C++ Code:(**"Iterative Approach"**)
32+
33+
```cpp
34+
class Solution {
35+
public:
36+
ListNode* middleNode(ListNode* head) {
37+
38+
int count=0;
39+
40+
ListNode *temp = head;
41+
42+
while(temp != NULL)
43+
{
44+
count++;
45+
46+
temp = temp->next;
47+
}
48+
49+
int Middle = count /= 2;
50+
51+
temp = head;
52+
53+
while(Middle--)
54+
{
55+
temp = temp->next;
56+
}
57+
return temp;
58+
59+
}
60+
};
61+
```

0 commit comments

Comments
 (0)