36.两个链表的第一个公共结点

    xiaoxiao2021-03-25  62

    题目描述 输入两个链表,找出它们的第一个公共结点。 1、解法1 首先,分别遍历两个链表,求出链表长度M、N,然后,让指向长链表的指针先走|M-N|步,然后,指向短链表的指针再往前走,当长短链表的指针指向同一个节点时,该节点就是他们的公共节点。

    public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int len1 = length(pHead1); int len2 = length(pHead2); if (len1 > len2){ pHead1 = walk(pHead1, len1 - len2); } else { pHead2 = walk(pHead2, len2 - len1); } while (pHead1 != pHead2){ pHead1 = pHead1.next; pHead2 = pHead2.next; } return pHead1; } int length(ListNode head) { int length = 0; while (head != null){ length++; head = head.next; } return length; } ListNode walk(ListNode head, int i) { while (i-- != 0){ head = head.next; } return head; } }

    2、解法2 把就两个链表连接起来,则连接起来的长度为M+N,这时候,无论短链表在前还是长链表在前,他们的公共节点部分一定是在连接链表的相同索引位置。例如: 1->3->5->7->9->10,2->7->9->10,按长短和短长两种方式连接后,得如下两个链表: 1->3->5->7 ->9->10->2->7->9->10 2->7->9->10->1-> 3->5->7-> 9->10 所以,有如下解法:

    public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode temp1 = pHead1; ListNode temp2 = pHead2; while (temp1 != temp2){ /* if (temp1 == null) temp1 = pHead2; else temp1 = temp1.next; if (temp2 == null) temp2 = pHead1; else temp2 = temp2.next; */ //简洁写法,if...else...都可以这样写 temp1 = (temp1 == null ? pHead2 : temp1.next); temp2 = (temp2 == null ? pHead1 : temp2.next); } return temp1;//当temp1 == temp2时,找到公共节点。 } }
    转载请注明原文地址: https://ju.6miu.com/read-37141.html

    最新回复(0)