两道链表的简单数学题
文章目录
1.环形链表
LC142环形链表II
配图证明:双指针的一个数学题
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == nullptr || head->next == nullptr) return nullptr;
ListNode* fast=head->next->next;
ListNode* slow=head->next;
while(slow!=fast){
if(fast==nullptr || fast->next==nullptr) return nullptr;
fast=fast->next->next;
slow=slow->next;
}
fast=head;
while(fast!=slow) {
fast=fast->next;
slow=slow->next;
}
return slow;
}
};
这个代码还是挺容易错的。
主要是这俩If语句
fast和slow的初始化。
当然用head初始化fast和slow也行,就是要把while改成do-while;
2.相交链表
LC160相交链表
证明:
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *h1=headA, *h2=headB;
while(h1!=h2)
{
h1=h1==nullptr? headB: h1->next;
h2=h2==nullptr? headA: h2->next;
}
return h1;
}
};
?:这个三目运算符用的很不错。