链表相交
题目链接面试题 02.07. 链表相交 - 力扣(LeetCode)
class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode* curA = headA; ListNode* curB = headB; int lenA = 0, lenB = 0 ; while(curA != NULL){ lenA++; curA = curA->next; } while(curB != NULL){ lenB++; curB = curB->next; } curA = headA; curB = headB; if(lenB > lenA){ swap(lenA, lenB); swap(curA, curB); } int dif; dif = lenA - lenB; while(dif--){ curA = curA->next; } while(curA != NULL){ if(curA == curB){ return curA; } curA = curA->next; curB = curB->next; } return NULL; } };
这道题解法关键是,相交的节点后面的节点也是相同的。所以两个链表的末尾一定是相等的。
所以只要使两个链表末尾对齐就可以进行查找,同样使用双指针法,快指针先移动链表长度差值的步数。还算逻辑比较清晰。
标签:lenB,ListNode,Day6,next,链表,curB,curA,LeetCode,刷题 From: https://www.cnblogs.com/tianmaster/p/16859445.html