LintCode:M-两个链表的交叉
来源:互联网 发布:金融行业数据分析软件 编辑:程序博客网 时间:2024/05/17 21:57
LintCode链接
请写一个程序,找到两个单链表最开始的交叉节点。
注意事项
- 如果两个链表没有交叉,返回
null
。 - 在返回结果后,两个链表仍须保持原有的结构。
- 可假定整个链表结构中没有循环。
样例
下列两个链表:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
在节点 c1 开始交叉。
挑战
需满足 O(n) 时间复杂度,且仅用 O(1) 内存。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { /** * @param headA: the first list * @param headB: the second list * @return: a ListNode */ public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode nodeA = headA; ListNode nodeB = headB; int sizeA=0, sizeB=0; while(nodeA!=null && nodeB!=null){ if(nodeA==nodeB) return nodeA; nodeA = nodeA.next; sizeA++; nodeB = nodeB.next; sizeB++; } while(nodeA!=null){ nodeA = nodeA.next; sizeA++; } while(nodeB!=null){ nodeB = nodeB.next; sizeB++; } if(sizeA>sizeB) return getCross(headA, headB, sizeA, sizeB); else return getCross(headB, headA, sizeB, sizeA); } ListNode getCross(ListNode longNode, ListNode shortNode, int longSize, int shortSize){ while(shortSize<longSize){ longNode = longNode.next; longSize--; } while(shortNode!=null){ if(longNode==shortNode) return shortNode; longNode = longNode.next; shortNode = shortNode.next; } return null; } }
阅读全文
0 0
- LintCode:M-两个链表的交叉
- Lintcode 两个链表的交叉
- LintCode: 两个链表的交叉
- lintcode ----两个链表的交叉
- lintcode-两个链表的交叉
- [LintCode]380.两个链表的交叉
- 两个链表的交叉-LintCode
- LintCode-剑指Offer-(380)两个链表的交叉
- lintcode刷题——两个链表的交叉
- LintCode(M)交叉字符串
- [Lintcode]Intersection of Two Linked Lists 两个链表的交叉
- lintcode 交叉链表
- 两个链表的交叉
- 两个链表的交叉
- 两个链表的交叉
- LintCode:M-带环链表
- LintCode 两个链表的和
- LintCode-两个链表的和
- 注销手机号,存在重大安全问题
- JS基础学习day1
- java按值传递(2)两整数交换
- NSNotificationCenter
- Redis实现参数的集中式管理
- LintCode:M-两个链表的交叉
- 关于操作 Python 列表,Top10最常见问答
- mybatis的选择查询,模糊查询
- 树莓派3.5寸屏幕和hdmi显示切换的方法
- STM32-modbus rtu 之主机程序
- Linux运维学习之路(5)Linux用户管理
- Fragment嵌套Fragment, TabLayout + ViewPager实现页面切换滑动
- java 时间类SimpleDateFormat,Date
- 针对过去时空数据的索引的几种分类方法