160:相交链表

(LeetCode160)相交链表

题目描述:编写一个程序,找到两个单链表相交的起始节点。如图:

思路: 

  1. 分别求出两个链表的长度,用长的减去短的就是长链表应该先走的步数
  2. 两个链表的节点同时移动,知道相遇则说明链表相交,若有链表走到空也没有相遇则说明没有相交,返回 null。

如上图,链表 A 的长度为 5 ,链表 B 的长度为 6,相减得到  diff = 1,则让较长的链表 B 走一步,到达 b2 节点,此时遍历 A, B两个链表,判断是否相交。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public int getLength(ListNode head){
        int len = 0;
        for(head = head;head != null;head = head.next){
            len++;
        }
        return len;
    }
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = getLength(headA);
        int lenB = getLength(headB);
        int diff = lenA - lenB;
        ListNode longer = headA;
        ListNode shorter = headB;
        if(diff < 0){
            longer = headB;
            shorter = headA;
            diff = -diff;
        }
        for(int i = 0;i < diff;i++){
            longer = longer.next;
        }
        while(longer != shorter){
            longer = longer.next;
            shorter = shorter.next;
        }
        return longer;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值