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;
        }
    };
    

      

  • 相关阅读:
    mysql性能优化
    jdbc connectoin timeout
    java thread dump
    sso实现原理
    api的防重放机制
    java各版本新特性总结
    sql区分大小写的查询
    按分数排名
    MySql常用语句
    mysql之explain用法
  • 原文地址:https://www.cnblogs.com/lautsie/p/4196785.html
Copyright © 2011-2022 走看看