160. Intersection of Two Linked Lists
来源:互联网 发布:nginx 视频服务器 编辑:程序博客网 时间:2024/05/15 00:23
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.
分析:因为其后面的元素都是一样的,先得出每个列表的长度,然后将长度长的往后移动直到其后面的长度和短的一样,然后逐渐判断和短的列表的元素是不是一样,不一样的话则都往后移一个。
时间复杂度:O(M)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA==null||headB==null) return null; int lena=0; int lenb=0; ListNode temp=headA; ListNode temp1=headB; while(temp!=null){ lena++; temp=temp.next; } while(temp1!=null){ lenb++; temp1=temp1.next; } if(lena<lenb){ temp1=headB; int i=lenb-lena; while(i>0){ temp1=temp1.next; i--; } temp=headA; }else{ temp=headA; int i=lena-lenb; while(i>0){ temp=temp.next; i--; } temp1=headB; } while(temp!=temp1){ temp=temp.next; temp1=temp1.next; } return temp; }}
0 0
- [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
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- SpringMVC 使用@ResponseBody 返回json 报错,一直不出来
- 程序无权限上传服务器和无法再服务器中创建文件夹的解决办法
- 正则表达式语法
- CLI PHP WebSocket服务器
- Android Service完全解析,关于服务你所需知道的一切(上)
- 160. Intersection of Two Linked Lists
- 虚函数知识
- seajs项目,js版本号带来的问题
- JavaScript入门(三) - 提问(prompt 消息对话框)
- 找数组中出现次数最多的一个
- Word2Vec
- Android主题与样式
- 第十二周课后作业——项目一——爬楼梯
- RxPermission解决Android 6.0 适配问题