代码随想录:链表相交
像做数学题一样,要挖掘出表象下的实际条件。
比如这道题,链表在一段时间后相交,其实含义是两者的尾部是相同的,所以只需要将尾部对齐即可。
/**
* 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 a_length = -1;
int b_length = -1;
ListNode* virta = new ListNode(0,headA);
ListNode* virtb = new ListNode(0,headB);
ListNode* targeta = virta;
ListNode* targetb = virtb;
while(targeta!=NULL){
targeta = targeta->next;
a_length++;
}
while(targetb!=NULL){
targetb = targetb->next;
b_length++;
}
targeta = virta;
targetb = virtb;
if(a_length>b_length){
for(int i=0;i<a_length-b_length;i++){
targeta = targeta->next;
}
}else{
for(int i=0;i<b_length-a_length;i++){
targetb = targetb->next;
}
}
while(targeta!=NULL){
if(targeta->next ==targetb->next){
return targeta->next;
}
targeta = targeta->next;
targetb = targetb->next;
}
return NULL;
}
};
标签:ListNode,int,targetb,随想录,相交,next,链表,targeta
From: https://www.cnblogs.com/huigugu/p/18559195