两个链表的第一个公共结点
2015-09-24 10:12
281 查看
输入两个链表,找出它们的第一个公共结点。
package linkedList;
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null || pHead2==null){
return null;
}
int len1=getLen(pHead1);
int len2=getLen(pHead2);
if(len1>len2){
int step=len1-len2;
while(step>0){
pHead1=pHead1.next;
step--;
}
}else if(len1<len2){
int step=len2-len1;
while(step>0){
pHead2=pHead2.next;
step--;
}
}
while(pHead1!=pHead2){
pHead1=pHead1.next;
pHead2=pHead2.next;
}
return pHead1;
}
public int getLen(ListNode pHead){
int len=0;
while(pHead!=null){
len++;
pHead=pHead.next;
}
return len;
}
}
package linkedList;
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null || pHead2==null){
return null;
}
int len1=getLen(pHead1);
int len2=getLen(pHead2);
if(len1>len2){
int step=len1-len2;
while(step>0){
pHead1=pHead1.next;
step--;
}
}else if(len1<len2){
int step=len2-len1;
while(step>0){
pHead2=pHead2.next;
step--;
}
}
while(pHead1!=pHead2){
pHead1=pHead1.next;
pHead2=pHead2.next;
}
return pHead1;
}
public int getLen(ListNode pHead){
int len=0;
while(pHead!=null){
len++;
pHead=pHead.next;
}
return len;
}
}
相关文章推荐
- Win7 Eclipse Hadoop2.4插件配置
- Win7 Eclipse Hadoop2.4插件配置
- HTTP页面请求的返回值
- 在JSP中如何使用JSTL(EL表达式)格式化日期
- Delphi关于TTask的外部中断&等待结束
- mtk智能机平台编译内核
- Linux守护进程log——syslog
- jps出现process information unavailable的问题
- 在Visual Studio 2013顯示SCSS詳細錯誤訊息
- web工程中友好的自定义错误返回页面
- [IOS 开发] sqlite 使用事务操作数据库
- CentOS 6.5下Redmine的安装配置
- jquery 获取 自定义属性(attr 和 prop)
- JUnit断言方法
- Windows系统Ionic安装教程/Ionic环境配置
- 网页常用动态效果--多表单验证
- Foundation框架2
- 但愿老死花酒间,不愿鞠躬车马前
- php中or, |, ||, 和and,&, &&之间的作用及区别
- 我与监控宝之间的点点滴滴