zoukankan      html  css  js  c++  java
  • 160. Intersection of Two Linked Lists

    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 };
  • 相关阅读:
    SpringCloud微服务基础学习
    EF6 + MySql 建立项目引用失败
    Forword(请求转发)与Redirect(重定向)区别
    Java 中 Hashtable与HashMap的区别
    cookie和session
    configparser模块的简单使用
    列表中的陷阱
    Python3面向对象编程总结
    Python---RabbitMQ的使用
    Django的template自定义函数的创建和使用
  • 原文地址:https://www.cnblogs.com/sankexin/p/5866153.html
Copyright © 2011-2022 走看看