Middle of the Linked List
Problem
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.
Solution Approach
Click - to see solution code
- C++
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* temp;
temp = new ListNode;
temp = head;
int cnt = 0;
while (temp != NULL) {
cnt++;
temp = temp->next;
}
int i = 1;
while (i <= cnt / 2) {
head = head->next;
i++;
}
return head;
}
};