Friday, December 28, 2018

[LeetCode]Middle of the Linked List

双指针的问题,两个指针一快一慢,快的每次移动2的距离,慢的移动1的距离即可。时间复杂度O(N),常数空间。代码如下:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* fast = head, *slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
};

No comments:

Post a Comment