[leetcode] 160. Intersection of Two Linked Lists 解题报告

题目链接:https://leetcode.com/problems/intersection-of-two-linked-lists/

Write a program to find the node at which the intersection of two singly linked lists begins.


For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.


Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

思路:先计算两个链表的长度,让长的先走他们长度的差值,然后这时候他们剩余长度相等了,再一起走,直到找到公共的结点,或者直到结束。恩,思路还是比较清晰的!Have a nice day!现在美国南卡时间凌晨2:22。夜还很漫长!奋斗

代码如下:

/**
 * 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 || !headB)  return NULL;
        int len1 = 0, len2 = 0;
        ListNode *p= headA, *q = headB;
        while(p)
        {
            len1++;
            p = p->next;
        }
        while(q)
        {
            len2++;
            q = q->next;
        }
        p = headA, q = headB;
        int i = 0;
        while(i < abs(len1 - len2))
        {
            if(len1 > len2)
                p = p->next;
            else
                q = q->next;
            i++;
        }
        while(p && q)
        {
            if(p != q)
            {
                p = p->next;
                q = q->next;
            }
            else
                return p;
        }
        return NULL;
    }
};


哦,看了下discus,发现一个极其简约的代码,不禁感叹想出这个方式的人好聪明!这种算法的思想是两个指针各走len1 + len2的长度,最后将会同步,然后判断是否相等,其时间复杂度是O(len1 + len2),比上一个时间复杂度略高,但是绝对是值得的。得意

代码如下:

/**
 * 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 || !headB)  return NULL;
        ListNode *p= headA, *q = headB;
        while(p != q)
        {
            p = p==NULL?headB:p->next;
            q = q==NULL?headA:q->next;
        }
        return p;
    }
};

参考:https://leetcode.com/discuss/66203/java-solution-without-knowing-the-difference-in-len


你可能感兴趣的:(LeetCode,算法,list,single)