Lintcode 两个链表的交叉
2015-10-28 23:44
253 查看
请写一个程序,找到两个单链表最开始的交叉节点。
您在真实的面试中是否遇到过这个题?
Yes
样例
下列两个链表:
在节点 c1 开始交叉。
注意
如果两个链表没有交叉,返回
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
挑战
需满足 O(n) 时间复杂度,且仅用 O(1) 内存。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// write your code here
int lenA = 0 , lenB = 0;
ListNode *pA = headA, *pB = headB; //这里定义了两个变量pA,pB;编程时候一定要注意,使用的时候一定要知道变量的当前值
while(pA )
{lenA++;pA = pA->next;}
while(pB )
{lenB++;pB = pB->next;}
int d = lenA -lenB;
pA = headA ;pB = headB;
if(lenA < lenB)
{
pA = headB;pB = headA;
d = lenB - lenA;
}
while(d > 0)
{
pA = pA->next;
d--;
}
while(pA != pB)
{
pA = pA->next;
pB = pB->next;
}
return pA;
}
};
您在真实的面试中是否遇到过这个题?
Yes
样例
下列两个链表:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
在节点 c1 开始交叉。
注意
如果两个链表没有交叉,返回
null。
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
挑战
需满足 O(n) 时间复杂度,且仅用 O(1) 内存。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// write your code here
int lenA = 0 , lenB = 0;
ListNode *pA = headA, *pB = headB; //这里定义了两个变量pA,pB;编程时候一定要注意,使用的时候一定要知道变量的当前值
while(pA )
{lenA++;pA = pA->next;}
while(pB )
{lenB++;pB = pB->next;}
int d = lenA -lenB;
pA = headA ;pB = headB;
if(lenA < lenB)
{
pA = headB;pB = headA;
d = lenB - lenA;
}
while(d > 0)
{
pA = pA->next;
d--;
}
while(pA != pB)
{
pA = pA->next;
pB = pB->next;
}
return pA;
}
};
相关文章推荐
- 野指针(悬挂指针)
- unity抛物线,平均速度下的运动轨迹
- uc手机浏览器使用animation的一个坑
- Lowest Common Ancestor of a Binary Search Tree
- 线程的生命周期
- codeforces 591A. Wizards' Duel 解题报告
- UIDevice的 UiSelector的讲解
- Xargs用法详解
- ip
- Java NIO (一)
- 好久没打开博客了
- Java中比较容易混淆的知识点
- 敏捷实况5:设计与敏捷
- Java 开源工具包
- 线段树的查询
- pyqt4 python2.7 中文乱码的解决方法
- android面试题
- android netty5局域网通讯(客户端+服务端)
- 10-2- Logistic Regression Error
- Oauth2.0与Oauth1.0的区别