Intersection of Two Linked Lists
2015-07-03 15:56
190 查看
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
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.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
Show Tags
Have you met this question in a real interview?
Yes
No
思路:假设listA的长度为m,listB的长度为n,只要A中有一个元素在B中出现,那么A,B从那个元素起,后面的都是重合的。
具体可见剑指offer的两个链表的第一公共节点那一题。
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.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
Show Tags
Have you met this question in a real interview?
Yes
No
思路:假设listA的长度为m,listB的长度为n,只要A中有一个元素在B中出现,那么A,B从那个元素起,后面的都是重合的。
具体可见剑指offer的两个链表的第一公共节点那一题。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { //剑指offer的第37题P194 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA==null||headB==null){ return null; } //求出ListA的长度和ListB的长度 int lenA = 0; ListNode pa = headA; int lenB = 0; ListNode pb = headB; while(pa!=null){ lenA++; pa = pa.next; } while(pb!=null){ lenB++; pb = pb.next; } //调整pa和pb的位置,使得大家的剩余长度一样。 pa = headA; pb = headB; if(lenB>lenA){ int c = lenB-lenA; while(c>0){ pb=pb.next; c--; } } if(lenA>lenB){ int c = lenA-lenB; while(c>0){ pa=pa.next; c--; } } //调整完毕,开始一个一个的比较,找公共点 while(pa!=null){ if(pa.val == pb.val){ return pa; }else{ pa = pa.next; pb = pb.next; } } return null; } }还有利用堆栈的方法来做,但是空间换时间,具体也见书上的分析。
相关文章推荐
- Android开发(八)——Android组件
- Android开发(七)——判断网络状态
- Android开发(六)——组件颜色Selector(Selector与Shape的基本用法 )
- Win8怎么打开Windows To Go功能有哪些方法
- python urllib
- Android repository 下载地址
- stl之list双向链表容器应用基础
- Jsoup学习笔记4:Jsoup 解析Html源码实例
- 1036. 跟奥巴马一起编程(15)
- Viewpager实现图片轮播,广告轮播
- 【JS】表单、JS在线编辑相关资料收集
- hibernate实现多表联合查询
- 基于Hash算法的高维数据的最近邻检索
- 树莓派2操作记录(有记录才能沉淀...)
- 查看图片
- Android开发(五)——计时器
- Android开发(四)——Android中的颜色
- 压缩及解压缩命令tar的使用
- javascript实现点击提交按钮后显示loading的方法
- Win10系统调整快速访问文件夹顺序按照访问时间来排序