【leetcode】160. 相交链表

题目: 160. 相交链表 - 力扣(LeetCode) (leetcode-cn.com)

思路:

要找到相交链表的第一个结点。可以先让链表A和链表B走相等的距离,指针第一次相遇时就是相交相交链表的第一个结点;

注意: 指针1走完A链表,再走B链表;指针2走完B链表,再走A链表;

代码如下:

/**
 * 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) {
        ListNode p1 = headA,p2=headB;
        while( p1 != p2){

            //指针1走完A链表,再走B链表;
            if(p1 != null){
                p1 = p1.next;
            }else{
                p1= headB;
            }
            // 指针2走完B链表,再走A链表;
            if(p2 != null){
                p2 = p2.next;
            }else {
                p2 = headA;
            }
        }

        return p1;
        
    }
}

 

posted @ 2022-05-01 19:50  MintMin  阅读(9)  评论(0编辑  收藏  举报