Chinaunix首页 | 论坛 | 博客
  • 博客访问: 984526
  • 博文数量: 150
  • 博客积分: 3017
  • 博客等级: 少校
  • 技术积分: 3829
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-19 14:40
个人简介

Now in Baidu WISE team

文章分类

全部博文(150)

文章存档

2014年(8)

2013年(31)

2012年(111)

分类: C/C++

2012-12-26 17:23:51

练手代码。(codepad.org 编译通过,未运行)
判断两个单链表是否相交,如相交的话求交点。
方法:
记录两个链表的长度差。然后长的那个先出发,当剩下的长度和短的相同时,短的链表也出发。
当两个链表遍历到结点相同时,为相交结点。
若两个链表无交点,则最后结点为NULL。直接返回即可

点击(此处)折叠或打开

  1. typedef struct tagNode{
  2.     int value;
  3.     struct tagNode* next;
  4. } Node;

  5. Node *getintersection(Node* llist1, Node* llist2){
  6.     if(llist1 == NULL || llist2 == NULL) return NULL;

  7.     int count1, count2;
  8.     count1 = count2 = 1;
  9.         Node* ptr1 = llist1;
  10.         Node* ptr2 = llist2;
  11.     while(ptr1!=NULL){
  12.         ptr1 = ptr1->next;
  13.         count1++;
  14.     }
  15.     while(ptr2!=NULL){
  16.         ptr2 = ptr2->next;
  17.         count2++;
  18.     }
  19.     
  20.     ptr1 = llist1;
  21.     ptr2 = llist2;

  22.     int dis = count1-count2;
  23.     while(dis>0){
  24.         ptr1 = ptr1->next;
  25.         dis--;
  26.     }

  27.     while(dis<0){
  28.         ptr2 = ptr2->next;
  29.         dis++;
  30.     }
  31.     
  32.     while(ptr1!=ptr2){
  33.         ptr1=ptr1->next;
  34.         ptr2=ptr2->next;
  35.     }
  36.         //if the 2 linked lists does not share the same end node,it will return NULL
  37.     return ptr1;
  38. }
  39. int main(){
  40.         return 0;
  41. }

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