leetcode_数据解构_链表_106相交链表

做题目录:

https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E7%9B%AE%E5%BD%95.md

160相交链表

本题的题意是找到两个链表中的相交结点(即从此结点之后两个链表即合并成了一个链表),而不是寻找两个链表中值相同的结点

一、暴力解法:

以链表1的每一个元素为第一层循环,链表2的每一个元素为第二层循环,每当链表2的元素遍历完一遍后,链表1的元素指针指向下一个链表1的元素,直到遍历完所有元素

代码:

/**
 * 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) {
        ListNode *p1=NULL;
        ListNode *p2=NULL;
        p1=headA;
        p2=headB;
        while(p1&&p2){
            if(p1==p2)return p1;
            p2=p2->next;
            if(p2==NULL){
                p1=p1->next;
                p2=headB;
            }
            if(p1==NULL)return NULL;
        }
        return NULL;
        
    }
};

 二、寻找链表相交结点的另一种解法:

两个链表相交,则自从相交结点开始,以后的两个链表的结点个数必定相同。首先算出两个链表的长度,算出两个链表的长度差x,然后另长的链表先遍历x个元素,然后再对两个链表的元素进行对应的一一遍历,若不为同一个结点,则两个链表的遍历指针同时往后移。

/**
 * 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 length1=0,length2=0;
        ListNode *p1=headA,*p2=headB;
        while(p1){
            length1++;
            p1=p1->next;
        }
        while(p2){
            length2++;
            p2=p2->next;
        }
        p1=headA;
        p2=headB;
        int step=(length1>=length2?length1-length2:length2-length1);
        if(length1>=length2){
            while(step--){
                p1=p1->next;
            }
        }
        else{
            while(step--){
                p2=p2->next;
            }
        }
        while(p1&&p2){
            if(p1==p2)return p1;
            p1=p1->next;
            p2=p2->next;
        }
        return NULL;
    }
};

 

posted @ 2021-06-13 16:02  SanFranciscoo  阅读(29)  评论(0编辑  收藏  举报