zoukankan      html  css  js  c++  java
  • [leetcode]Intersection of Two Linked Lists

    又是个老提

    先判断是否相交,如果相交,那么两个链表最后的节点是一样的。

    相交那么,我们就来找相交的那个点,假设两个链表一样长,一起往后走,到相同的那个就是交点,不一样长,我们把长的切掉,然后继续这样找就好了。

    /**
     * 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) {
            if (headA == nullptr || headB == nullptr) return nullptr;
            int la = 0;
            int lb = 0;
            ListNode* tmpA = headA;
            ListNode* tmpB = headB;
            while(tmpA -> next != nullptr) {
                la++;
                tmpA = tmpA -> next;
            }
            while(tmpB -> next != nullptr) {
                lb++;
                tmpB = tmpB -> next;
            }
            if (tmpA != tmpB) return nullptr;
            tmpA = headA;
            tmpB = headB;
        
            if (lb < la) {
            // la must less than lb
                swap(tmpA, tmpB);
                swap(la, lb);
            }
            int diff = lb - la;
            for (int i = 0; i < diff; i++) {
                tmpB = tmpB -> next;
            }
        
            while (tmpA != tmpB) {
                tmpA = tmpA -> next;
                tmpB = tmpB -> next;
            }
            return tmpA;
        }
    };
  • 相关阅读:
    数字证书原理(转)
    python update from 2.6 to 2.7
    python uwsgi 部署以及优化
    uWSGI配置(转 )
    Python程序的性能分析指南(转)
    mysql 暴力破解 root账号密码
    VMware虚拟机实用经验总结十一条
    小技巧之指定refer
    cookie和session
    web相关
  • 原文地址:https://www.cnblogs.com/x1957/p/4127492.html
Copyright © 2011-2022 走看看