Chinaunix首页 | 论坛 | 博客
  • 博客访问: 143005
  • 博文数量: 66
  • 博客积分: 1571
  • 博客等级: 上尉
  • 技术积分: 715
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-24 22:55
文章分类

全部博文(66)

文章存档

2012年(66)

我的朋友

分类: C/C++

2012-09-21 09:55:58

 

点击(此处)折叠或打开

  1. ListNode * FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2)

  2. {

  3.       // Get the length of two lists

  4.       unsigned int nLength1 = ListLength(pHead1);

  5.       unsigned int nLength2 = ListLength(pHead2);

  6.       int nLengthDif = nLength1 - nLength2;
  7.  
  8.      // Get the longer list

  9.       ListNode *pListHeadLong = pHead1;

  10.       ListNode *pListHeadShort = pHead2;

  11.       if(nLength2 > nLength1)

  12.       {
  13.             pListHeadLong = pHead2;

  14.             pListHeadShort = pHead1;

  15.             nLengthDif = nLength2 - nLength1;

  16.       }
  17.       // Move on the longer list

  18.       for(int i = 0; i < nLengthDif; ++ i)

  19.             pListHeadLong = pListHeadLong->m_pNext;
  20.       // Move on both lists

  21.       while((pListHeadLong != NULL) &&

  22.             (pListHeadShort != NULL) &&

  23.             (pListHeadLong != pListHeadShort))

  24.       {
  25.             pListHeadLong = pListHeadLong->m_pNext;

  26.             pListHeadShort = pListHeadShort->m_pNext;
  27.       }
  28.       // Get the first common node in two lists

  29.       ListNode *pFisrtCommonNode = NULL;

  30.       if(pListHeadLong == pListHeadShort)

  31.             pFisrtCommonNode = pListHeadLong;
  32.       return pFisrtCommonNode;

  33. }
  34. ///////////////////////////////////////////////////////////////////////

  35. // Get the length of list with head pHead

  36. // Input: pHead - the head of list

  37. // Return: the length of list

  38. ///////////////////////////////////////////////////////////////////////

  39. unsigned int ListLength(ListNode* pHead)

  40. {
  41.       unsigned int nLength = 0;

  42.       ListNode* pNode = pHead;

  43.       while(pNode != NULL)

  44.       {
  45.             ++ nLength;

  46.             pNode = pNode->m_pNext;

  47.       }


  48.       return nLength;

  49. }

阅读(1160) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~