LeetCode刷题(9.28)
编写一个程序,找到两个单链表相交的起始节点。
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
思路:找到两个链表相同的起始位置,然后开始遍历
代码实现:
/**
* 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) {
int lenA = 0, lenB = 0;
//求链表长度
ListNode pA = headA;
ListNode pB = headB;
while (pA != null) {
pA = pA.next;
++lenA;
}
while (pB != null) {
pB = pB.next;
++lenB;
}
pA = headA;
pB = headB;
// 让长的链表先走完这段差值
if(lenA-lenB>0){
for(int i = 0; i < lenA-lenB;i++){
pA = pA.next;
}
}else if(lenA - lenB < 0){
for(int i = 0; i< lenB-lenA;i++){
pB = pB.next;
}
}
// 然后两指针同时走
while (pA != pB) {
pA = pA.next;
pB = pB.next;
}
return pA;
}
}
看了评论区的解答还有一种思路比较简单,本质还是找到两个链表相同的起始位置,然后开始遍历。
让pA和pB从头开始遍历,以上图为例,pA先遍历完链表A, 然后让pA指向headB, 继续遍历链表B。等到pB遍历完链表B, 再让pB指向headA, 这时pA和pB就到达了相同的位置。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) return null;
ListNode pA = headA, pB = headB;
while(pA != pB) {
//判断pA是否到达链表结尾,如果到达,让pA=headB,否则继续向后移动
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pA;
}
}