TreeviewCopyright © aleen42 all right reserved, powered by aleen42

52. 两个链表的第一个公共节点

https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/

Java

/**
 * 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(headA == null || headB == null) return null;
       // 题目要求: 勿破坏原链表结构
       ListNode nodeA = headA, nodeB = headB;
       // 循环遍历链表
       while(nodeA != nodeB) {
            // 若nodeA到了末尾,则令nodeA = headB,然后继续遍历
            nodeA = nodeA == null ? headB : nodeA.next;
            // 若nodeB到了末尾,则令nodeB = headA,然后继续遍历
            nodeB = nodeB == null ? headA : nodeB.next;
       }
       // 返回结果
       return nodeA;
    }
}

Python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        # 判断头节点是否为空
        if not headA or not headB: return None
        # 题目要求: 勿破坏原链表结构
        nodeA, nodeB = headA, headB
        # 循环遍历链表
        while(nodeA != nodeB):
            # 如果nodeA到了末尾,则令nodeA = headB,然后继续遍历
            nodeA = nodeA.next if nodeA else headB
            # 若nodeB到了末尾,则令nodeB = headA,然后继续遍历
            nodeB = nodeB.next if nodeB else headA
        # 返回结果
        return nodeA
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""