国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

160. Intersection of Two Linked Lists

2019-11-08 02:45:37
字體:
來源:轉載
供稿:網友

題目

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.


思路

先遍歷兩個鏈表求出各自的長度,分別用兩個指針指向其頭結點,長的那個鏈表節點先往后走兩者長度的差值個數節點,這樣可以保證當兩者相遇時肯定同時相遇,再同時往后遍歷,直到走到NULL或者相遇


代碼

/** * 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 lengthA = 0; int lengthB = 0; ListNode* tempA = headA; ListNode* tempB = headB; while(tempA != NULL) { lengthA++; tempA = tempA->next; } while(tempB != NULL) { lengthB++; tempB = tempB->next; } tempA = headA; tempB = headB; //A更長 if(lengthA > lengthB) { for(int i=0;i < lengthA - lengthB;i++) { tempA = tempA->next; } } else { for(int i=0;i < lengthB - lengthA;i++) { tempB = tempB->next; } } while(tempA && tempB) { if(tempA == tempB) { return tempA; } tempA = tempA->next; tempB = tempB->next; } return NULL; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 楚雄市| 深泽县| 搜索| 青冈县| 亚东县| 那坡县| 平舆县| 化州市| 外汇| 德阳市| 麟游县| 专栏| 乐平市| 响水县| 通州市| 南平市| 阿巴嘎旗| 黄大仙区| 盐源县| 福州市| 九龙城区| 本溪市| 新化县| 长海县| 红原县| 罗平县| 广河县| 松潘县| 惠州市| 沛县| 固阳县| 运城市| 吴旗县| 长寿区| 长春市| 太康县| 香港 | 延长县| 邯郸县| 周口市| 周口市|