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

聪明的我看到链表就跳过了暴力解法和栈,直接想到了双指针。

即:两个链表同时往后遍历,直到较短链表达到结尾,这时设置较长链表的新头指针,随着尾工作指针向后遍历,达到结尾时,相当于得到了两个相同长度的链表,这时再从头往后寻找公共节点即可。

时间复杂度O(m+n)。

(对象==是判断其是否在同一个内存地址,即可用这个判断公共节点)。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1==null||pHead2==null) return null;
        
        ListNode p1=pHead1,p2=pHead2;
        while(p1!=null&&p2!=null){
            p1=p1.next;
            p2=p2.next;
        }
        if(p1==null){
            ListNode p4=pHead2;
            while(p2!=null){
                p2=p2.next;
                p4=p4.next;
            }
            pHead2=p4;
        }else{
            ListNode p3=pHead1;
            while(p1!=null){
                p1=p1.next;
                p3=p3.next;
            }
            pHead1=p3;
        }
        p1=pHead1;p2=pHead2;
        while(p1!=null&&p2!=null&&p1!=p2){
            p1=p1.next;
            p2=p2.next;
        }
        if(p1==null||p2==null)
            return null;
        return p1;
    }
}

运行时间:14ms

占用内存:9532k

 

暴力解法则是,挨个遍历所有节点对并对比O(mn)。

另外还可以用两个栈,后入先出,倒着对比节点是否相同。时间O(m+n)空间O(m+n)

 

python代码思路正确但是好像有点小问题:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        if pHead1 is None or pHead2 is None:
            return None
        p1 = pHead1; p2 = pHead2
        while p1 is not None and p2 is not None:
            p1=p1.next;p2=p2.next
        if p1 is None:
            pNewHead = p2
            while p2 is not None:
                p2=p2.next;pNewHead=pNewHead.next
            return self.helper(p1,pNewHead)
        else:
            pNewHead = p1
            while p1 is not None:
                p1=p1.next;pNewHead=pNewHead.next
            return self.helper(p2,pNewHead)
        
    def helper(self,p1,p2):
        while p1 is not p2 and p1 is not None and p2 is not None:
            p1=p1.next;p2=p2.next
        if p1 is None or p2 is None:
            return None
        else:
            return p1

 

posted @ 2019-03-01 11:56  大胖子球花  阅读(122)  评论(0)    收藏  举报