题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { struct ListNode *p1=pHead1; struct ListNode *p2=pHead2; while(p1!=p2){ // 只能运行一步,因此需要写一块 if(p1==nullptr){ p1=pHead2; }else{ p1 = p1->next; } //即使某个为空,也可以 if(p2==nullptr){ p2=pHead1; }else{ p2 = p2->next; } } return p1; } };
无论是判断为空(指向另一个链表),还是指向本身的next,都算作一次操作,因此只能执行一个。
即使一个为null,也是拼接另一个,因此不用额外考虑