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

    老题了。

    class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            ListNode *tailA = headA;
            ListNode *tailB = headB;
            int lengthA = getLength(headA, tailA);
            int lengthB = getLength(headB, tailB);
            if (tailA != tailB || tailA == NULL) {
                return NULL;
            }
            ListNode *nodeA = headA;
            ListNode *nodeB = headB;
            int diff = abs(lengthA - lengthB);
            while (diff--) {
                if (lengthA > lengthB) {
                    nodeA = nodeA->next;    
                } else {
                    nodeB = nodeB->next;
                }
            }
            while (nodeA != nodeB) {
                nodeA = nodeA->next;
                nodeB = nodeB->next;
            }
            return nodeA;
        }
        
        int getLength(ListNode *head, ListNode *&tail) {
            if (head == NULL) {
                tail = NULL;
                return 0;
            }
            int length = 1;
            ListNode *node = head;
            while (node->next != NULL) {
                node = node->next;
                length++;
            }
            tail = node;
            return length;
        }
    };
    

      

  • 相关阅读:
    python解析网页
    node.js 爬虫
    c++ split实现
    foldl foldr
    爬虫http header gzip
    命令[10]
    命令[08]
    命令[15]
    命令[13]
    命令[11]
  • 原文地址:https://www.cnblogs.com/lautsie/p/4196785.html
Copyright © 2011-2022 走看看