160. Intersection of Two Linked Lists leetcode (list)
来源:互联网 发布:网络主播招聘要求 编辑:程序博客网 时间:2024/04/29 18:54
- 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:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(NULL == headA || NULL == headB) //如果两个链表有一个为空则返回空,不存在相交的点 { return NULL; } ListNode *p1 = headA; ListNode *p2 = headB; ListNode * result=NULL; //用来保存结果的节点 int len1 = 0; int len2 = 0; while(p1) //遍历获得链表1的长度 { len1++; p1 = p1->next; } while(p2)//遍历获得链表2的长度 { len2++; p2 = p2->next; } if(len2 > len1)//使得p1始终指向长的链表,p2指向短的链表 { p1 = headB; p2 = headA; } else { p1 = headA; p2 = headB; } int len = abs(len1 - len2); while(len) //长的链表先走完长的节点 { p1 = p1->next; len--; } while(p1&&p2) { if(p1->val == p2->val) //如果相等则找到相交的节点 { result = p1; break; } else { p1 = p1->next; p2 = p2->next; } } return result; }
//最开始提交的代码错误的原因,我去~~~~~~~ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(NULL == headA || NULL == headB) { return NULL; } ListNode *p1 = headA; ListNode *p2 = headB; int len1 = 0; int len2 = 0; while(p1) { len1++; p1 = p1->next; } while(p2) { len2++; p2 = p2->next; } p1 = headA; //注意这两句不能少,开始就是因为缺少这两句,我去~~~~~~~~~~~ p2 = headB; int num = abs(len1 - len2); while(num) { if(len1 >len2) { p1 = p1->next; //cout<<" 1 p1->val="<<p1->val<<" "; } else { p2 = p2->next; } num--; } while(p1 && p2) { if(p1->val== p2->val) { return p1; break; } p1 = p1->next; p2 = p2->next; } return NULL; }
0 0
- 160. Intersection of Two Linked Lists leetcode (list)
- [leetcode][list] Intersection of Two Linked Lists
- [LeetCode]160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160.Intersection of Two Linked Lists
- [leetcode] 160.Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode *** 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode-160. Intersection of Two Linked Lists
- LeetCode-160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- Android studio 用SVN Share 项目出现 Authentication required 的问题
- 有1,2,2,3,4,5六个数,要求输出他们组合的全排列
- EF更新数据库结构seed方法不执行
- MATLAB robotics tools工具箱下载安装
- Python知识点汇总
- 160. Intersection of Two Linked Lists leetcode (list)
- 数据结构经典面试题——练习4
- 关于Java EE的介绍
- SQL Server中,删除表,删除表中数据
- Python3 + django 支持 MySQL
- Android 中MVP基本认识和 用法
- 设计模式——备忘录模式
- hyperledger 搭建
- DedeCMS织梦系统服务器端安装