题意
给定两个链表,找这两个链表第一个公共节点,如果没有返回nullptr
题目链接
https://leetcode.com/problems/intersection-of-two-linked-lists/description/
题解
两个指针分别从两个链表(记录为表A,表B)的表头出发,并且记录到表尾移动的步数,得到两个指针移动的步数之差 x x x。步数之差为正数,那么把表A的指针移动 x x x步,否则移动表B的指针 − x -x −x步。然后两个指针移动到表尾,得到答案。
/*** 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 *p1 = headA;ListNode *p2 = headB;int cnt1 = 0;int cnt2 = 0;while(p1) {p1 = p1->next;cnt1++;}while(p2) {p2 = p2->next;cnt2++;}p1 = headA;p2 = headB;int cnt3 = abs(cnt1 - cnt2);if(cnt1 >= cnt2) {for(int i = 0; i < cnt3; i++) {p1 = p1->next;}} else {for(int i = 0; i < cnt3; i++) {p2 = p2->next;} }while(p1 != p2 && p1 != nullptr) {p1 = p1->next;p2 = p2->next;}return p1 == nullptr ? nullptr : p1;}
};
算法复杂度: O ( m + n ) O(m+n) O(m+n), m m m, n n n分别为两个表的长度
空间复杂度: O ( 1 ) O(1) O(1)