1. 程式人生 > >劍指offer-兩個連結串列第一個公共結點

劍指offer-兩個連結串列第一個公共結點

36.兩個連結串列第一個公共結點

題目描述

輸入兩個連結串列,找出它們的第一個公共結點。

解題思路:用兩重迴圈,對第一個連結串列的每一個結點都進行第二個連結串列所有結點的遍歷,若發現結點相等,則將結點返回

 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {    
        while(pHead1!=null)
        {
           ListNode head=pHead2;
            while(head!=null)
            {
                if(pHead1==head)
                    return pHead1;
                else
                    head=head.next;
            }
            pHead1=pHead1.next;
        }
        return null; 
    }

解題思路2:若連結串列相交,則連結串列的最後一個結點一定相同,計算出兩個連結串列的長度差d,長的連結串列先走d步,然後兩個連結串列指標同時走,當結點相等時,則返回此結點。

 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1==null || pHead2==null)
            return null;
        int len1=0;
        int len2=0;
        ListNode head1=pHead1;
        ListNode head2=pHead2;
        while(head1!=null)
        {
            len1++;
            head1=head1.next;
        }
        while(head2!=null)
        {
            len2++;
            head2=head2.next;
        }
        head1=pHead1;
        head2=pHead2;
        if(len1>=len2)
        {
            for(int i=0;i<len1-len2;i++)
            {
                head1=head1.next;
            }
        }
        else
        {
            for(int i=0;i<len2-len1;i++)
            {
                head2=head2.next;
            }
        }
        while(head1!=head2 && head1!=null)
        {
            head1=head1.next;
            head2=head2.next;
        }
        if(head1==null)
            return null;
        else
            return head1;        
    }

解題思路3:由於兩個連結串列的最後一個結點相同,則可以從最後一個結點向前找,直到第一個相同的結點,由於連結串列只能從前向後查詢,所以我們可以用棧來進行上述操作

 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
         if(pHead1==null || pHead2==null)
             return null;
        Stack<ListNode> stack1=new Stack<>();
        Stack<ListNode> stack2=new Stack<>();
        ListNode node=null;
        while(pHead1!=null)
        {
            stack1.push(pHead1);
            pHead1=pHead1.next;           
        }
        while(pHead2!=null)
        {
            stack2.push(pHead2);
            pHead2=pHead2.next;
        }
        if(stack1.peek()!=stack2.peek())
            return null;
        while(!stack1.isEmpty() && !stack2.isEmpty() && stack1.peek()==stack2.peek())
        {
            node=stack1.pop();
            stack2.pop();
        }
        return node;    
    }