码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer系列源码

时间:2014-12-10 18:03:58      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   sp   for   strong   on   

两个链表的第一个公共结点

两个链表相交成Y型。

#include <iostream>
#include <stdio.h>
using namespace std;
struct ListNode{
    int value;
    ListNode* next;
};
unsigned int getListLength(ListNode* pHead){
    unsigned int length = 0;
    ListNode* pNode = pHead;
    while(pNode){
        length++;
        pNode = pNode->next;
    }
    return length;
}
ListNode* findFirstCommonNode(ListNode* pHead1,ListNode* pHead2){
    unsigned int length1 = getListLength(pHead1);
    unsigned int length2 = getListLength(pHead2);
    int lengthDif = length1-length2;
    ListNode* pListHeadLong = pHead1;
    ListNode* pListHeadShort = pHead2;
    if(length1<length2){
        pListHeadLong = pHead2;
        pListHeadShort = pHead1;
        lengthDif =length2-length1;
    }
    for(int i=0;i<lengthDif;i++){
        pListHeadLong = pListHeadLong->next;
    }
    while(pListHeadLong&&pListHeadShort&&pListHeadLong!=pListHeadShort){
        pListHeadLong = pListHeadLong->next;
        pListHeadShort = pListHeadShort->next;
    }
    ListNode* pFirstCommonNOde = pListHeadLong;
    return pFirstCommonNOde;
}
int main() {
	return 0;
}


剑指offer系列源码

标签:style   blog   io   color   os   sp   for   strong   on   

原文地址:http://blog.csdn.net/hackcoder/article/details/41849001

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!