首页 > 代码库 > [leetcode]Intersection of Two Linked Lists
[leetcode]Intersection of Two Linked Lists
老题了。
class Solution {public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *tailA = headA; ListNode *tailB = headB; int lengthA = getLength(headA, tailA); int lengthB = getLength(headB, tailB); if (tailA != tailB || tailA == NULL) { return NULL; } ListNode *nodeA = headA; ListNode *nodeB = headB; int diff = abs(lengthA - lengthB); while (diff--) { if (lengthA > lengthB) { nodeA = nodeA->next; } else { nodeB = nodeB->next; } } while (nodeA != nodeB) { nodeA = nodeA->next; nodeB = nodeB->next; } return nodeA; } int getLength(ListNode *head, ListNode *&tail) { if (head == NULL) { tail = NULL; return 0; } int length = 1; ListNode *node = head; while (node->next != NULL) { node = node->next; length++; } tail = node; return length; }};
[leetcode]Intersection of Two Linked Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。