题目:输入两个链表,找出它们的第一个公共节点。
解法一:利用HashSet,比较捞
解法二:双指针
思路:两个链表长度分别为m+C、n+C, C为公共部分的长度,第一个人走完一轮后,回到第二个人起点走n步;第2个人走了n+C步后,回到第一个人起点走m步。 此时它们因走的步数相同而相遇。
代码:
/**
- Definition for singly-linked list.
- public class ListNode {
-
int val;
-
ListNode next;
-
ListNode(int x) {
-
val = x;
-
next = null;
-
}
- }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headAnull||headBnull){
return null;
}
ListNode p = headA;
ListNode q = headB;
while(p!=q){
if(pnull){ //用if else的好处是:当它们没有公共节点时,会因为都等于null而退出循环
p=headB;
} else{
p=p.next;
}
if(qnull){
q=headA;
} else{
q=q.next;
}
}
return p;
}
}
剑指 Offer 52. 两个链表的第一个公共节点
原文:https://www.cnblogs.com/nickyBlog/p/13945873.html