您的位置:首页 > 其它

[LeetCode]Intersection of Two Linked Lists

2014-12-04 15:10 465 查看
Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

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.
有几种方式来处理

方法1:遍历A List中的每个结点,逐个检查该结点是否在B列表中存在,若存在,该结点即为第一个公共结点,否则返回NULL

方法2:先计算A和B的长度之差delta,然后选择长的一个列表,先走delta步,然后同时遍历2个列表,相同的第一个结点即为公共结点

方法3:遍历列表A,加上访问标记,遍历列表B,碰到的第一个有标记的结点即为第一个公共结点,清除列表A的标记,返回公共结点或者NULL

下面附上方法3的代码流程,

#define mark(node) (node->next = (ListNode*)(int(node->next)|0x1))
#define unmark(node) (node->next = (ListNode*)(int(node->next)&~0x1))
#define isMarked(node) (int(node->next) & 0x1)

ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode*node,*l1,*l2;
node = NULL;
l1= headA,l2=headB;
//vist A list and mark
while(l1){
node = l1->next;
mark(l1);
l1 = node;
}

while(l2){
if(isMarked(l2)){
unmark(l2);
node = l2;
break;
}
l2 = l2->next;
}

//clear the marked flag
l1 = headA;
while(l1){
unmark(l1);
l1 = l1->next;
}

return node;
}

该方法Leetcode测试通过
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法