LeetCode 160. Intersection of Two Linked Lists

来源:互联网 发布:八爪鱼按摩淘宝 编辑:程序博客网 时间:2024/04/29 06:29

Write a program to find the node at which the intersection of two singly linked lists begins.


For example, the following two linked lists:

A:          a1 → a2                   ↘                     c1 → c2 → c3                   ↗            B:     b1 → b2 → b3

begin to intersect at node c1.


Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

一、算法分析

首先求出两个链表的长度,然后计算长度差。让较长的链表先走长度差个节点,然后两个链表节点同时进行遍历,如果节点指针相等则退出。如果最后指针都为NULL,那么说明没有交叉节点,返回NULL;否则,返回交叉节点。

二、C语言实现

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {    int lengthA=0,lengthB=0,n;    struct ListNode *p,*q;    p=headA;    while(p){        lengthA++;        p=p->next;    }    p=headB;    while(p){        lengthB++;        p=p->next;    }    n=lengthA-lengthB;    p=headA;    q=headB;    if(n>0){//A长一些,那么就要先从A走出去几个        while(n--){            p=p->next;        }    }else{        n=abs(n);        while(n--){            q=q->next;        }    }    while(p!=q){        p=p->next;        q=q->next;    }    if(q==NULL && p==NULL)        return NULL;    return p;}


0 0