前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Intersection of Two Linked Lists

Leetcode: Intersection of Two Linked Lists

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-25 14:44:42
3770
发布2019-01-25 14:44:42
举报

题目:

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

代码语言:javascript
复制
A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

思路分析:

因为两个List的长度不一样,所以先分别算出两个List的长度,然后设置一个指针指向较长的List的(长-短)的位置,这样子较长List从该位置开始到最后的长度和较短List相同,然后遍历两个List如果有相同的Node则返回。

代码示例:

代码语言:javascript
复制
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
private:
    int length(ListNode *head)
    {
    	int count = 0;
    	ListNode *p = head;
    	while (p)
    	{
    		count++;
    		p = p->next;
    	}
    	return count;
    }
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
    {
    	if (headA == NULL || headB == NULL)
    	{
    		return NULL;
    	}
    
    	int lengthA = length(headA);
    	int lengthB = length(headB);
    	
    	int offLength = lengthA - lengthB;
    	if (offLength < 0)
    	{
    		offLength *= -1;
    	}
    
    	ListNode *pa = headA;
    	ListNode *pb = headB;
    	for (int i = 0; i < offLength; i++)
    	{
    		if (lengthA > lengthB)
    		{
    			pa = pa->next;
    		}
    		else
    		{
    			pb = pb->next;
    		}
    	}
    
    	while (pa != pb)
    	{
    		pa = pa->next;
    		pb = pb->next;
    	}
    	return pa;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年03月07日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档