相交链表

 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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int len1=len(headA);
        int len2=len(headB);
        //把两条链表变得一样长
        if(len1<len2){
            for(int i=0;i<len2-len1;i++){
                headB=headB->next;
            }
        }
        if(len1>len2){
            for(int i=0;i<len1-len2;i++){
                headA=headA->next;
            }
        }
        //指针同步后移,判断对应结点的值是否相等,但要记得判断结点是不是NULL
        while(headA!=NULL && headB!=NULL && headA!=headB){
            headA=headA->next;
            headB=headB->next;
        }
        if(headA==headB) return headA;
        else return NULL;    
    }
    //计算链表长度
    int len(ListNode *head)
    {
        int count=0;
        while(head!=NULL){
            head=head->next;
            count++;
        }
        return count;
    }
};

 

 
原文地址:https://www.cnblogs.com/Bipolard/p/9988206.html