Java for LeetCode 160 Intersection of Two Linked Lists
2015-06-05 17:19
537 查看
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.
解题思路:
先遍历两个list的长度,然后长的减去短的,之后同时遍历即可,JAVA实现如下:
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
解题思路:
先遍历两个list的长度,然后长的减去短的,之后同时遍历即可,JAVA实现如下:
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA==null||headB==null) return null; int lengthA=0,lengthB=0; ListNode tempA=headA,tempB=headB; while(tempA!=null){ tempA=tempA.next; lengthA++; } while(tempB!=null){ tempB=tempB.next; lengthB++; } if(lengthB>lengthA){ tempA=headA; headA=headB; headB=tempA; int temp=lengthA; lengthA=lengthB; lengthB=temp; } int length=lengthA-lengthB; while(length-->0) headA=headA.next; while(headA!=null){ if(headA==headB) return headA; headA=headA.next; headB=headB.next; } return headA; }
相关文章推荐
- 简单页面下载实例
- Java中特殊的String
- Mac下修改Android Studio 所用的JDK版本
- javac命令和jar命令
- JAVA WEB项目中文乱码问题解决方案
- Java 基本方法连接数据库并且执行查询,你发现这个会有什么问题吗
- java随笔
- java Properties工具
- 顺手笔记---javac,javap,javah
- Java反射机制详解。
- javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher--转载
- Java语言描述:分支限界法之01背包问题
- Java for LeetCode 155 Min Stack
- Combination Sum III Leecode Java
- Java多线程用法解析
- java返回编码格式
- java 线程池优先级调度
- java琐碎
- Java for LeetCode 154 Find Minimum in Rotated Sorted Array II
- Java Word 转 Pdf