本文主要是介绍leetcode No160. Intersection of Two Linked Lists,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Question:
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.
Algorithm:
Accepted Code:
/*** 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==NULL || headB==NULL)return NULL;stack<ListNode*> s1;stack<ListNode*> s2;ListNode *p1=headA;ListNode *p2=headB;while(p1){s1.push(p1);p1=p1->next;}while(p2){s2.push(p2);p2=p2->next;}ListNode *res=NULL;while((!s1.empty() && !s2.empty()) && s1.top()==s2.top()){res=s1.top();s1.pop();s2.pop();}return res;}
};
/*** 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 len1=0;int len2=0;ListNode *p1=headA;ListNode *p2=headB;while(p1){p1=p1->next;len1++;}while(p2){p2=p2->next;len2++;}int lendiff=0;ListNode *pHeadLong=NULL;ListNode *pHeadShort=NULL;if(len1>len2){pHeadLong=headA;pHeadShort=headB;lendiff=len1-len2;}else{pHeadLong=headB;pHeadShort=headA;lendiff=len2-len1;}for(int i=0;i<lendiff;i++)pHeadLong=pHeadLong->next;while(pHeadLong!=NULL && pHeadShort!=NULL && pHeadShort!=pHeadLong){pHeadLong=pHeadLong->next;pHeadShort=pHeadShort->next;}ListNode *res=pHeadLong;return res;}
};
class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {ListNode* p1=headA;ListNode* p2=headB;while(p1!=p2){if(p1!=NULL)p1=p1->next;elsep1=headB;if(p2!=NULL)p2=p2->next;elsep2=headA;}return p1;}
};
这篇关于leetcode No160. Intersection of Two Linked Lists的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!