Find the first intersection of two lists (if the two list are merged at some point)
来源:互联网 发布:sift算法的优缺点 编辑:程序博客网 时间:2024/05/04 15:47
http://www.geeksforgeeks.org/write-a-function-to-get-the-intersection-point-of-two-linked-lists/
Method 3(Using difference of node counts)
1) Get count of the nodes in first list, let count be c1.
2) Get count of the nodes in second list, let count be c2.
3) Get the difference of counts d = abs(c1 – c2)
4) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes.
5) Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes)
/* function to get the intersection point of two linked lists head1 and head2 */int getIntesectionNode(struct node* head1, struct node* head2){ int c1 = getCount(head1); int c2 = getCount(head2); int d; if(c1 > c2) { d = c1 - c2; return _getIntesectionNode(d, head1, head2); } else { d = c2 - c1; return _getIntesectionNode(d, head2, head1); }}/* function to get the intersection point of two linked lists head1 and head2 where head1 has d more nodes than head2 */int _getIntesectionNode(int d, struct node* head1, struct node* head2){ int i; struct node* current1 = head1; struct node* current2 = head2; for(i = 0; i < d; i++) { if(current1 == NULL) { return -1; } current1 = current1->next; } while(current1 != NULL && current2 != NULL) { if(current1 == current2) return current1->data; current1= current1->next; current2= current2->next; } return -1;}/* Takes head pointer of the linked list and returns the count of nodes in the list */int getCount(struct node* head){ struct node* current = head; int count = 0; while (current != NULL) { count++; current = current->next; } return count;}
0 0
- Find the first intersection of two lists (if the two list are merged at some point)
- 【Hackerrank】Find the merge point of two joined linked lists
- [leetcode][list] Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- 用c语言实现 Hermite Polynomials(厄密多项式)
- PHP内置server
- 52.N-Queens II
- ovs图形化监控工具
- IA64与x86-64的区别
- Find the first intersection of two lists (if the two list are merged at some point)
- ArcGIS中用数据生成线和面的方法
- iOS开发~禁用文本输入框拷贝和粘贴等功能
- TA人经验之谈个人发展等
- 期刊知识
- SpringMVC前台ajax传递一位数组
- AngularJS自学之路(三)——控制器和表达式
- TCP/IP网络通信原理
- 学习大数据的网站