Intersection of Two Linked Lists
来源:互联网 发布:天津医科大学考研知乎 编辑:程序博客网 时间:2024/05/19 22:59
题意:给定两个链表,找到两个链表相交的地方
解法:遍历两个链表的长度,然后找到长链表中和短链表中长度相同的节点,开始同时遍历直到找到共同节点
复杂度:时间O(m+n),空间O(1)
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null) return null; ListNode a = headA; ListNode b = headB; int lena = 0; int lenb = 0; while(a!=null) { lena++; a=a.next; } while(b!=null) { lenb++; b=b.next; } a = headA; b = headB; if(lena>lenb) { while(lena>lenb) { lena--; a=a.next; } } else { while(lenb>lena) { lenb--; b=b.next; } } while(a!=null&&a!=b) { a=a.next; b=b.next; } return a; }}
0 0
- 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
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- 《构建高性能web站点》读书随笔目录
- mongodb模糊查询
- MATLAB神经网络编程(五)——BP神经网络的模型结构与学习规则
- mysql优化一
- HDU 2187 A sequence of numbers【快速幂】
- Intersection of Two Linked Lists
- 2、安卓控件 ExitText
- HDU 2191 (多重背包)
- 结构-06. 复数四则运算(15)
- 编写程序,读入未指定个数的整数,判断读入的整数有多少个,读入的负数有多少个
- java socket编程 (转)
- java 编程----显示一个整数的所有最小因子
- Linux一些经典书籍
- 4.3 TCP Splice