160.相交链表
①解决思路
方法1:分别测出A,B链表的长度,再记录它们的差值,先使较长的链表走差值步,然后两个链表同时向后移动,当某一时刻它们指向的下一地址相同时那么下一地址就为相交点。
②代码实践
方法1
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{
struct ListNode* tailA = headA, *tailB = headB;
int lenA, lenB;
lenA = lenB = 1;
while (tailA->next)
{
lenA++;
tailA = tailA->next;
}
while (tailB->next)
{
lenB++;
tailB = tailB->next;
}
if (tailA != tailB)
{
return NULL;
}
int mul = abs(lenA - lenB);
struct ListNode* longer = headA, *shorter = headB;
if (lenA < lenB)
{
longer = headB;
shorter = headA;
}
while (mul--)
{
longer = longer->next;
}
while (shorter != longer)
{
shorter = shorter->next;
longer = longer->next;
}
return longer;
}
141.环形链表
①解决思路
方法1:使用快慢指针,快指针一次走两步,慢指针一次走一步,因为相差的步长为一步,所以如果有环的话最终慢指针会追上快指针,而如果没有环的话快指针就会先一步走到空。
②代码实践
bool hasCycle(struct ListNode *head)
{
struct ListNode* fast, *slow;
fast = slow = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (fast == slow)
{
return true;
}
}
return false;
}