【题目】
给定两个(单向)链表,判定它们是否相交并返回交点。请注意相交的定义基于节点的引用,而不是基于节点的值。换句话说,如果一个链表的第k个节点与另一个链表的第j个节点是同一节点(引用完全相同),则这两个链表相交。
来源:leetcode
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
【代码】
执行用时 :52 ms, 在所有 C++ 提交中击败了90.58% 的用户
内存消耗 :14.6 MB, 在所有 C++ 提交中击败了100.00%的用户
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int callen(ListNode* listnode){
int cnt=0;
while(listnode){
listnode=listnode->next;
cnt++;
}
return cnt;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *shortlist=headA,*longlist=headB,*listnode;
if(!headA||!headB)
return NULL;
int lenA=callen(shortlist),lenB=callen(longlist);
int diff=lenB-lenA;
if(lenA>lenB){
swap(shortlist,longlist);
diff=abs(diff);
}
while(diff--){
longlist=longlist->next;
}
while(shortlist){
if(shortlist==longlist)
break;
shortlist=shortlist->next;
longlist=longlist->next;
}
return shortlist;
}
};
【set】时间复杂度高相比上一个代码简洁
执行用时 :144 ms, 在所有 C++ 提交中击败了8.22% 的用户
内存消耗 :21.4 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
set<ListNode*> s;
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
while(headA){
s.insert(headA);
headA=headA->next;
}
while(headB){
if(s.count(headB))
return headB;
s.insert(headB);
headB=headB->next;
}
return NULL;
}
};
【双指针大法】虽然设计思想很巧妙,但是性能堪忧。不过比set法性能高一点。
执行用时 :72 ms, 在所有 C++ 提交中击败了36.25% 的用户
内存消耗 :14.4 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* nodeA=headA,*nodeB=headB;
while(nodeA!=nodeB){
if(!nodeA)
nodeA=headB;
else
nodeA=nodeA->next;
if(!nodeB)
nodeB=headA;
else
nodeB=nodeB->next;
}
return nodeA;
}
};