自学内容网 自学内容网

leetcode160相交列表

思路

一开始以为要固定A,然后循环B,这个复杂度也太高了

题解:
https://leetcode.cn/problems/intersection-of-two-linked-lists/?envType=study-plan-v2&envId=top-100-liked
在这里插入图片描述
在这里插入图片描述

代码

/**
 * 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 pa = headA;
        ListNode pb = headB;
        int flag = 0;
        while (true){
            if (pa == null){
                flag++;
                pa = headB;
            }
            if (pb == null){
                flag++;
                pb = headA;
            }
            if (flag == 2){
                break;
            }
            pa = pa.next;
            pb = pb.next;
        }
        while (true){
            if (pa == pb){
                return pa;
            }
            pa = pa.next;
            pb = pb.next;
        }
    }
}

原文地址:https://blog.csdn.net/weixin_44554979/article/details/142354421

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!