标签:next node val 无效 inf code ref 一起 ++
编写一个程序,找到两个单链表相交的起始节点。力扣
解法一:剑指offer中思路,先计算两个链表长度(lengthA, lengthB),然后长链表先走(lengthA-lengthB)步后,两个链表一起走,相等节点即为要找的节点。
/** * 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) { if (headA == nullptr || headB == nullptr) //无效输入 return nullptr; ListNode *pNodeA = headA, *pNodeB = headB; int lengthA = 0, lengthB = 0; for (; pNodeA != nullptr; ++lengthA) //计算链表A长度 pNodeA = pNodeA->next; for (;pNodeB != nullptr; ++lengthB) //计算链表B长度 pNodeB = pNodeB->next; int diff = lengthA - lengthB; //此处默认链表A更长 pNodeA = headA; //记得重新赋值,这里忘掉了 pNodeB = headB; if (diff < 0) //否则交换 { diff = lengthB - lengthA; pNodeA = headB; pNodeB = headA; } for (int i = 0; i < diff; ++i) //长链表先走 pNodeA = pNodeA->next; while (pNodeA != pNodeB && pNodeA != nullptr && pNodeB != nullptr) //两个链表节点相等时跳出 { pNodeA = pNodeA->next; pNodeB = pNodeB->next; } return pNodeA; } };
解法二:思路类似于上述代码。
/** * 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 *pNodeA = headA, *pNodeB = headB; while (pNodeA != pNodeB) { pNodeA = (pNodeA == nullptr) ? headB : pNodeA->next; pNodeB = (pNodeB == nullptr) ? headA : pNodeB->next; } return pNodeA; } };
如果只是判断是否存在交点,有两种解法:
LeetCode 160. 相交链表 Intersection of Two Linked Lists (Easy)
标签:next node val 无效 inf code ref 一起 ++
原文地址:https://www.cnblogs.com/ZSY-blog/p/12804338.html