zoukankan      html  css  js  c++  java
  • 两个链表的第一个公共节点

    思路:

    利用栈的思想,从尾到头进行比较。空间复杂度O(M+N),时间复杂度O(M+N);

    利用双指针,首先遍历两个链表的长度,让长的链表先走 比短链表长的 步数,然后同时在两个链表上遍历,找到的第一个相同的结点就是他们的第一个公共的节点。

     1 /*
     2 struct ListNode {
     3     int val;
     4     struct ListNode *next;
     5     ListNode(int x) :
     6             val(x), next(NULL) {
     7     }
     8 };*/
     9 class Solution {
    10 public:
    11     ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
    12         int len1 = getlistlength(pHead1);
    13         int len2 = getlistlength(pHead2);
    14         int firststep = len1-len2;
    15         ListNode* longnode = pHead1;
    16         ListNode* shortnode = pHead2;
    17         if(len2>len1){
    18             longnode = pHead2;
    19             shortnode = pHead1;
    20             firststep = len2-len1;
    21         }
    22         for(int i=0;i<firststep;i++){
    23             longnode = longnode->next;
    24         }
    25         while(longnode && shortnode && longnode!=shortnode){
    26             longnode = longnode->next;
    27             shortnode = shortnode->next;
    28         }
    29         //此时已经到了第一个公共的节点
    30         return longnode;
    31 }
    32     int getlistlength(ListNode* pHead){
    33         int length=0;
    34         while(pHead){
    35             length++;
    36             pHead = pHead->next;
    37         }
    38         return length;
    39     }
    40 };
  • 相关阅读:
    分数加减法
    两点距离
    1的个数
    Swift 了解(1)
    ARC快速入门
    ARC基本概念
    autorelease注意事项
    autorelease基本使用
    NSTimer的使用
    如何监听控件的行为
  • 原文地址:https://www.cnblogs.com/pacino12134/p/11180699.html
Copyright © 2011-2022 走看看