剑指offer14-两个链表的第一个公共节点

325 阅读2分钟

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

题目描述

输入两个链表,找出它们的第一个公共节点。

思路1

  • 用两个指针扫描”两个链表“,最终两个指针到达 null 或者到达公共节点。(*****)
程序(java)
    /**
     * code1
     * 时间复杂度:O(),空间复杂度:O(1)
     */
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null || pHead2 == null) {
            return null;
        }

        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        while (p1 != p2) {
            p1 = (p1 != null ? p1.next : pHead2);
            p2 = (p2 != null ? p2.next : pHead1);
        }
        return p1;
    }
}
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/

思路2

  • 如果两个链表有公共节点,那么公共节点出现在两个链表的尾部。运用两个辅助栈:分别把两个链表的节点放入栈里,这样两个链表的尾结点就位于两个栈的栈顶,接下来比较两个栈顶的节点是否相同。如果相同,则把栈顶弹出接着比较下一个栈顶,直到找到最后一个相同的节点。
程序(java)
    /**
     * code2
     * 时间复杂度:O(m+n),空间复杂度:O(1)
     */
import java.util.Stack;
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
    if (pHead1 == null || pHead2 == null) {
            return null;
        }
        Stack<ListNode> stack1 = new Stack<>();
        Stack<ListNode> stack2 = new Stack<>();
 
        while (pHead1 != null) {
            stack1.push(pHead1);
            pHead1 = pHead1.next;
        }
 
        while (pHead2 != null) {
            stack2.push(pHead2);
            pHead2 = pHead2.next;
        }
 
        ListNode commonListNode = null;
 
        while (!stack1.isEmpty() && !stack2.isEmpty() && stack1.peek() == stack2.peek() ) {
            stack2.pop();
            commonListNode = stack1.pop();;
        }
 
        return commonListNode;
    }
}

思路3

  • 首先遍历两个链表得到它们的长度length1、length2,如果链表长度不相同,则在第二次遍历的时候,在较长的链表上先走(length1-length2)步,接着同时在两个链表上遍历,找到的第一个相同的节点就是它们的第一个公共节点。
程序(java)
    /**
     * code3
     * 时间复杂度:O(m+n),空间复杂度:O(1)
     */
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1==null||pHead2==null){
            return null;
        }
        if(pHead1==pHead2){
            return pHead1;
        }
        int length1=0;
        int length2=0;
        ListNode p1=pHead1;
        ListNode p2=pHead2;
        while(p1!=null){
            length1++;
            p1=p1.next;
        }
        while(p2!=null){
            length2++;
            p2=p2.next;
        }
        if(length1-length2<0){
            ListNode temp=pHead2;
            pHead2=pHead1;
            pHead1=temp;
        }
        int count=(length1-length2)>0?(length1-length2):(length2-length1);
        while(count--!=0){
            pHead1=pHead1.next;
        }
        while(pHead1!=pHead2){
            pHead1=pHead1.next;
            pHead2=pHead2.next;
            if(pHead1==null||pHead2==null){
                return null;
            }
        }
        return pHead1;
    }
}