[LeetCode]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.

这道题是求两个链表的共同后缀。共同后缀的判定不是两个指针所指向的值相等,,而是p1=p2,即指针本身相等。 简单粗暴的做法就是两重循环;这里做个优化,假设headA比headB的链表短,则headA从头开始,而headB从(lenB-lenA)开始扫描。

/** * 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) {ListNode* p1=headA;ListNode* p2=headB;ListNode* shorter;while(p1&&p2){p1=p1->next;p2=p2->next;}if(!p1){shorter=headA;p1=headB;}else{shorter=headB;p2=p1;p1=headA;}while(p2){p1=p1->next;p2=p2->next;}p2=shorter;while(p1){if(p1==p2)return p1;p1=p1->next;p2=p2->next;}return NULL;}};

联系朋友别欠费,天空辽阔任你飞,再多困难别后退! “

[LeetCode]Intersection of Two Linked Lists

相关文章:

你感兴趣的文章:

标签云: