Jan 06, Intersection of Two Linked Lists

一开始试着用DP去解决, 可是两个指针怎么同步移动很费劲,想了一会脑子混乱,就建立双向linked list,思路就很清晰了。

 

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA, preA = headA, nexA = null;
ListNode curB = headB, preB = headB, nexB = null;

if(curA == null || curB == null) return null;
while(curA != null && curA.next != null){
preA.next = nexA;
nexA = preA;
preA = curA.next;
curA = curA.next;
}
while(curB != null && curB.next != null){
preB.next = nexB;
nexB = curB;
curB = curB.next;
preB = curB;
}

if(preA == preB){
while(preA == preB && preA != null && preB != null && preA.next != null && preB.next != null ){
preA = preA.next;
preB = preB.next;
}
return preA;
}
else return null;
}
}

 

结果: 报错! No intersection, ERROR: linked structure was modified. 不该修改链表结构

 

别人de思路 用两个指针分别从headA 和 headB,通过跳转到另一个达到第二次遍历的时候 两个指针能指向对映的位置。

public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA, curB = headB;
if(curA == null || curB == null) return null;
while(curA != curB){
curA = curA == null ? headB : curA.next;
curB = curB == null ? headA : curB.next;
}
return curA;
}
}

转载于:https://www.cnblogs.com/5683yue/p/5111859.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值