160Intersection of Two Linked Lists
来源:互联网 发布:软件测试shell脚本 编辑:程序博客网 时间:2024/06/08 16:18
/*
* 解题思路:因为要找公共点,所以应该以短的为标准,
* 短的链从头开始,长的从对应位置开始(从此处到末尾的长度与短链整体长度相同)
* 然后逐一比较对应位置上的值是否相等,第一个相等处即为交叉点
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null) return null;
ListNode f = headA;
ListNode s = headB;
int f_len = 0;
int s_len = 0;
while(f!=null){
f = f.next;
++f_len;
}
while(s!=null){
s = s.next;
++s_len;
}
ListNode longer = null, shorter = null;
int dis = 0;
if(f_len >= s_len){
longer = headA;
shorter = headB;
dis = f_len - s_len;
}else if(f_len < s_len){
longer = headB;
shorter = headA;
dis = s_len - f_len;
}
if(f_len!=s_len){
for(int i=0;i<dis;++i){
longer = longer.next;
}
}
while(longer!=null&&shorter!=null){
if(longer.val==shorter.val){
return longer;
}else{
longer = longer.next;
shorter = shorter.next;
}
}
return null;
}
}
* 解题思路:因为要找公共点,所以应该以短的为标准,
* 短的链从头开始,长的从对应位置开始(从此处到末尾的长度与短链整体长度相同)
* 然后逐一比较对应位置上的值是否相等,第一个相等处即为交叉点
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null) return null;
ListNode f = headA;
ListNode s = headB;
int f_len = 0;
int s_len = 0;
while(f!=null){
f = f.next;
++f_len;
}
while(s!=null){
s = s.next;
++s_len;
}
ListNode longer = null, shorter = null;
int dis = 0;
if(f_len >= s_len){
longer = headA;
shorter = headB;
dis = f_len - s_len;
}else if(f_len < s_len){
longer = headB;
shorter = headA;
dis = s_len - f_len;
}
if(f_len!=s_len){
for(int i=0;i<dis;++i){
longer = longer.next;
}
}
while(longer!=null&&shorter!=null){
if(longer.val==shorter.val){
return longer;
}else{
longer = longer.next;
shorter = shorter.next;
}
}
return null;
}
}
0 0
- leetcode 160-Intersection of Two Linked Lists
- 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
- 160Intersection 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 160Intersection of Two Linked Lists
- LeetCode 160 :Intersection of Two Linked Lists
- 160Intersection of Two Linked Lists
- #160 Intersection of Two Linked Lists
- leetcode[160]:Intersection of Two Linked Lists
- 160 Intersection of Two Linked Lists
- MVP on Android
- C Language Study - 数组和指针的区别(1)
- 图片的镜像和倒影
- makefile教材
- 树的直径,树的重心,树的分冶
- 160Intersection of Two Linked Lists
- opencv 打开摄像头却捕捉不到图像解决方法
- 算法学习之排序算法(二)(直接插入排序法)
- 补间动画
- 属性动画
- 减少颜色数目
- NOIP模拟8.12总结
- hdu 5360 Hiking (贪心+优先队列)
- JSP学习笔记(七):session