两个链表重叠部分查找(Leetcode160)

2018-11-12  本文已影响0人  zhouwaiqiang

题目

解析

寻找相等路径

源代码

/**
 * 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 first = headA, second = headB;
        boolean markedA = false, markedB = false;
        while (first != null && second != null) {
            if (first == second) return first;//找到对应的节点
            if (first.next == null && !markedA) {
                first = headB;
                markedA = true;
            } else first = first.next;
            if (second.next == null && !markedB) {
                second = headA;
                markedB = true;
            } else second = second.next;
        }
        return null;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读