zoukankan      html  css  js  c++  java
  • LeetCode 160. 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) {
            
           int lenA = fun(headA);
           int lenB = fun(headB);
            
           int posA=lenA;
           int posB=lenB;
            
            ListNode* termA = headA;
            ListNode* termB = headB;
            
            ListNode* ans=NULL;
            
            while(termA!=NULL&&termB!=NULL)
            {
                if(posA<posB)
                {
                    termB=termB->next;
                    posB--;
                    continue;
                }
                else if(posA>posB)
                {
                    termA=termA->next;
                    posA--;
                }
                else
                {
                    if(termA==termB)
                    {
                        ans=termA;
                        break;
                    }
                    
                    termA=termA->next;
                    termB=termB->next;
                }
            }
            
            return ans;
            
        }
        
        int fun(ListNode* head)
        {
            int ans=0;
            ListNode* term = head;
            while(term!=NULL)
            {
                ans++;
                term=term->next;
            }
            
            return ans;
        }
        
        
    };
    
  • 相关阅读:
    第十六周总结
    第十五周学习进度
    输出最长字符串链
    第二阶段冲刺10
    第二阶段冲刺09
    第二阶段冲刺08
    输入法评价
    第十四周进度总结
    collections模块
    shutil模块(了解)
  • 原文地址:https://www.cnblogs.com/dacc123/p/12221440.html
Copyright © 2011-2022 走看看