程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 160. Intersection of Two Linked Lists,intersectionlinked

160. Intersection of Two Linked Lists,intersectionlinked

編輯:C++入門知識

160. Intersection of Two Linked Lists,intersectionlinked


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.

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
12         if(!headA){
13             return NULL;
14         }else if(!headB){
15             return NULL;
16         }
17         ListNode* ListLong = headA;
18         ListNode* ListShort = headB;
19         
20         int length1 = GetListLength(headA);
21         int length2 = GetListLength(headB);
22         int diffLength = length1 - length2;
23         
24         if(length2 > length1){
25             ListLong = headB;
26             ListShort = headA;
27             diffLength = length2 - length1;
28         }
29         
30         for(int i = 0 ; i < diffLength; i++){
31             ListLong = ListLong->next;
32         }
33         
34         while((ListLong != NULL) && (ListShort != NULL) && (ListLong != ListShort)){
35             ListLong = ListLong->next;
36             ListShort = ListShort->next;
37         }
38         
39         ListNode* CommonNode = ListLong;
40         return CommonNode;
41         
42     }
43     unsigned int GetListLength(ListNode* pHead){
44         unsigned int length = 0;
45         ListNode* pNode = pHead;
46         while(pNode != NULL){
47             ++length;
48             pNode = pNode->next;
49         }
50         return length;
51     }
52 };

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved