lintcode-medium-Intersetion of Two Linked Lists
2016-03-23 09:01
423 查看
Write a program to find the node at which the intersection of two singly linked lists begins.
The following two linked lists:
begin to intersect at node c1.
The following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
/** * 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) { // Write your code here if(headA == null || headB == null) return null; ListNode p1 = headA; ListNode p2 = headB; int len1 = 0; int len2 = 0; while(p1 != null){ len1++; p1 = p1.next; } while(p2 != null){ len2++; p2 = p2.next; } p1 = headA; p2 = headB; if(len1 > len2){ for(int i = 0; i < len1 - len2; i++) p1 = p1.next; } else if(len2 > len1){ for(int i = 0; i < len2 - len1; i++) p2 = p2.next; } while(p1 != null && p2 != null && p1 != p2){ p1 = p1.next; p2 = p2.next; } return p1; } }
相关文章推荐
- FIRST
- 装饰模式
- 转载:Java虚拟机体系结构
- week4b:个人博客作业
- 2016年Web前端面试题目
- 软件工程结对开发作业01-02
- Esxi主机与VCSA从6.0升级至6.0 U2
- struts Tag标签使用
- eclipse ADT
- 【集合框架】JDK1.8源码分析之LinkedList(七)
- android中handler和bundle有什么区别和联系 都是用来传递消息吗都是信息的载体吗
- 战火引擎中如何写Lua逻辑脚本
- iOS面试必看,最全梳理
- apache+tomcat分布式搭建
- 技术选型——混编APP应用概述
- 技术选型——混编APP应用概述
- sql中in和exists的区别效率问题
- 为啥公司愿花更多钱从外面招人
- 移动前端头部标签(HTML5 head meta)
- 网易2016春招实习笔试总结