• Leetcode 160 Intersection of Two Linked Lists 单向链表


    找出链表的交点, 如图所示的c1, 如果没有相交返回null.

    A:             a1 → a2
                                   ↘
                                       c1 → c2 → c3
                                  ↗           
    B:     b1 → b2 → b3

    我的方法是:

    (1)统计两个链表的长度

    (2)移动较长的链表的表头,使得让两个链表的长度一致

    (3)从修正后的表头出发对比两个链表的节点是否一致,输出一致的节点,否则输出null

     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     int list_len(ListNode* head){
    12         int cnt = 0;
    13         for(ListNode* now = head; now; now = now->next){
    14             ++cnt;
    15         }
    16         return cnt;
    17     }
    18     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    19         int al = list_len(headA);
    20         int bl = list_len(headB);//(1)
    21         ListNode* minh = headA;
    22         ListNode* maxh = headB;
    23         int cnt = bl - al;
    24         if(al > bl) {
    25             maxh = headA;
    26             minh = headB;
    27             cnt = -cnt;
    28         }
    29         while(cnt--){
    30             maxh = maxh->next;
    31         }                         //(2)
    32         for( ;maxh && minh ; maxh = maxh->next, minh = minh->next){
    33             if(maxh == minh) return maxh;
    34         }
    35         return NULL; //(3)
    36     }
    37 };
  • 相关阅读:
    redis持久化RDB和AOF
    线程同步的几种方法
    JRE和JDK的区别
    Spring-两种配置容器
    为什么String类是不可变的?
    Oracle 每五千条执行一次的sql语句
    Executor , ExecutorService 和 Executors
    常见框架单例、多例与线程安全性总结
    mysql 的S 锁和X锁的区别
    linux下使用shell脚本自动化部署项目
  • 原文地址:https://www.cnblogs.com/onlyac/p/5263308.html
Copyright © 2020-2023  润新知