problems: add middle of the linked list
This commit is contained in:
parent
b600d8cc67
commit
671fe591f6
1 changed files with 27 additions and 0 deletions
27
problems/middle-of-the-linked-list.cpp
Normal file
27
problems/middle-of-the-linked-list.cpp
Normal file
|
@ -0,0 +1,27 @@
|
|||
/**
|
||||
* Definition for singly-linked list.
|
||||
* struct ListNode {
|
||||
* int val;
|
||||
* ListNode *next;
|
||||
* ListNode() : val(0), next(nullptr) {}
|
||||
* ListNode(int x) : val(x), next(nullptr) {}
|
||||
* ListNode(int x, ListNode *next) : val(x), next(next) {}
|
||||
* };
|
||||
*/
|
||||
class Solution {
|
||||
public:
|
||||
ListNode* middleNode(ListNode* head) {
|
||||
auto slow = head;
|
||||
auto fast = head ? head->next : nullptr;
|
||||
|
||||
while (fast != nullptr) {
|
||||
slow = slow->next;
|
||||
fast = fast->next;
|
||||
if (fast) {
|
||||
fast = fast->next;
|
||||
}
|
||||
}
|
||||
|
||||
return slow;
|
||||
}
|
||||
};
|
Loading…
Reference in a new issue