[LeetCode] 面试题 02.07. 链表相交
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] 面试题 02.07. 链表相交
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
LeetCode 面試題 02.07.鏈表相交
思路
題目的本意其實就是求兩個鏈表相交處結點的指針,并返回該結點指針 步驟: Step1.分別用兩個指針curA、curB指向兩個鏈表A、B的頭結點 Step2.求出鏈表A與鏈表B的鏈表長度 Step3.實現兩個鏈表末尾對齊,并且讓curA與curB在同一起始結點上 Step4.循環遍歷兩個鏈表,遇到相同的結點則直接返回代碼
class Solution { public:int getListLength(ListNode *cur){int len = 0;while(cur != nullptr){len++;cur = cur->next;}return len;}ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {// step1.分別用兩個指針curA、curB指向兩個鏈表A、B的頭結點ListNode *curA = headA;ListNode *curB = headB;// step2.求出鏈表A與鏈表B的鏈表長度int lenA = getListLength(curA);int lenB = getListLength(curB);// curA = headA;// curB = headB;// step3.實現兩個鏈表末尾對齊,并且讓curA與curB在同一起始結點上if(lenA < lenB){swap(curA, curB);swap(lenA, lenB);}int gap = lenA - lenB;while(gap--){curA = curA->next;}// step4.循環遍歷兩個鏈表,遇到相同的結點則直接返回while(curA != nullptr){if(curA == curB){return curA;}curA = curA->next;curB = curB->next;}return nullptr;} };總結
以上是生活随笔為你收集整理的[LeetCode] 面试题 02.07. 链表相交的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 好用的识别植物的软件app合集分享,快码
- 下一篇: Angular在洋葱圈的实践与思考