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

原题

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

Reference Answer

思路分析

将链表中节点放入list后进行操作,对这种确定公共节点,计算数目之类的问题无往不利。

# -*- 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 not pHead1 or not pHead2:
            return None
        temp = []
        start1 = pHead1
        start2 = pHead2
        while start1:
            temp.append(start1)
            start1 = start1.next
        while start2:
            if start2 in temp:
                return start2
            start2 = start2.next
        return None
                            

上述方式太过暴力,时空复杂度都是 O(n);
该题的空间复杂度是可以降为 O(1)的,下面是优化版。

优化版:

我们也可以先让把长的链表的头砍掉,让两个链表长度相同,这样,同时遍历也能找到公共结点。此时,时间复杂度O(m+n),空间复杂度为O(1)。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        
        if (pHead1 == nullptr || pHead2 == nullptr){
            return nullptr;
        }
        ListNode* head1 = pHead1;
        ListNode* head2 = pHead2;
        ListNode* temp1 = head1;
        ListNode* temp2 = head2;
        int length = 0;
        while (head1 && head2){
            head1 = head1->next;
            head2 = head2->next;
            length ++;
        }
        while(head1){
            temp1 = temp1->next;
            head1 = head1->next;
        }
        while(head2){
            temp2 = temp2->next;
            head2 = head2->next;
        }
        while (temp1 && temp2){
            if (temp1 == temp2){
                return temp1;
            }
            temp1 = temp1->next;
            temp2 = temp2->next;
        }
        return NULL;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值