leetcode[160]:Intersection of Two Linked Lists
2015-06-07 19:25
393 查看
Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
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.
两个表后对齐,砍掉较长的表的前段,一个个元素比较就是了。
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
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.
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { int i,l1,l2; struct ListNode *L,*tmp; L = headA; if (headA == NULL || headB == NULL) return NULL; for( i = 0; L != NULL; i++) { L = L->next; } l1 = i; L = headB; for( i=0; L != NULL;i++) { L = L->next; } l2 = i; if (l1 > l2) { L = headA; for( i = 0 ; i < l1 - l2 ; i ++ ) { L = L->next; } tmp = headB; while(L!= NULL) { if(L->val == tmp->val) return L; L = L->next; tmp = tmp->next; } return NULL; } else { L = headB; for( i = 0 ; i < l2 - l1 ; i ++ ) { L = L->next; } tmp = headA; while(L!= NULL) { if(L->val == tmp->val) return L; L = L->next; tmp = tmp->next; } return NULL; } }
两个表后对齐,砍掉较长的表的前段,一个个元素比较就是了。
相关文章推荐
- C#中Ilist与list的区别小结
- C#中IList<T>与List<T>的区别深入解析
- C#对list列表进行随机排序的方法
- C++实现的泛型List类分享
- C# Datagridview绑定List方法代码
- javascript radio list的实现细节(多浏览器兼容)
- c++ STL容器总结之:vertor与list的应用
- 大家注意vector, list, set, map成员函数erase
- ASP.NET―001:GridView绑定List、页面返回值具体实现
- List all the Databases on a SQL Server
- js Map List 遍历使用示例
- Java List双击事件实现方法
- velocity显示List与Map的方法详细解析
- 关于STL中list容器的一些总结
- 关于C#泛型列表List<T>的基本用法总结
- Java集合类中文介绍
- use jscript with List Proxy Server Information
- list泛型自定义排序示例
- C#中IEnumerable、ICollection、IList、List之间的区别
- Perl List::Util模块使用实例