国产探花免费观看_亚洲丰满少妇自慰呻吟_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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 江门市| 丰宁| 聂荣县| 镇平县| 普陀区| 克东县| 盐亭县| 新闻| 洮南市| 富裕县| 铜川市| 科尔| 泗水县| 宝山区| 壤塘县| 长岛县| 大港区| 长沙县| 泾源县| 岳池县| 关岭| 农安县| 旬邑县| 突泉县| 庆安县| 涟水县| 铜陵市| 鱼台县| 曲阜市| 延津县| 泰州市| 区。| 宝应县| 江川县| 凭祥市| 乌兰浩特市| 岫岩| 三江| 天长市| 榆社县| 垫江县|