判断两个链表是否有公共节点并返回第一个公共节点

来源:互联网 发布:linux 找不到命令 编辑:程序博客网 时间:2024/04/19 06:03

判断两个链表是否有公共节点的方法最简单的就是遍历到每个链表的最后一个节点,看他们是否是同一个节点:如果是同一个节点的话,那么两个链表肯定有公共节点:

解释:因为链表是线性结构,不想树那样的非线性分叉结构

从链表的定义,就知道:

[c-sharp] view plaincopy
  1. typedef struct LNode{  
  2.     int data;  
  3.     struct LNode *next;  
  4. }LNode, *LinkList;  
 

一个链表有唯一的一个后序节点:如果两个链表中出现了公共节点,那么从该点开始,后面的节点都是公共的,肯定链表的最后一个节点也是公共的。于是不管三七二十一,遍历到最后链表的一个节点,判断两个节点是不是同一个节点就可以了。

但是这里我们要返回第一个公共节点,所以还得寻去他法:

1.如果两个链表有长度一样,我们从第一个逐个遍历节点,再比较是不是同一个节点就可以了;

2.如果两个链表长度不一样,我们应该先让长的链表从表头“走” len1 - len2步(len1为list1的长度,len2为list2的长度),然后按照1中方法进行操作即可。

[c-sharp] view plaincopy
  1. # include <stdio.h>  
  2. # include <malloc.h>  
  3. typedef struct LNode{  
  4.     int data;  
  5.     struct LNode *next;  
  6. }LNode, *LinkList;  
  7. /** 
  8.  * 采用数组a[]来初始化链表,数组的长度为length;head指向了头节点。 
  9.  */  
  10. LinkList CreatList(int a[], int length)  
  11. {  
  12.     LinkList head = (LinkList)malloc(sizeof(LNode));  
  13.     head->next = NULL;  
  14.     int index;  
  15.     LinkList temp;  
  16.     for (index = 0; index < length; index ++)  
  17.     {  
  18.         temp = (LinkList)malloc(sizeof(LNode));  
  19.         temp->data = a[index];  
  20.         temp->next = head->next;  
  21.         head->next = temp;  
  22.     }  
  23.     return head;  
  24. }  
  25. /** 
  26.  * 判断链表list1与链表list2是否相交,如果相交的话,就返回第一个相交点 
  27.  * 注意相交的话,就是横着的Y字型 
  28.  */  
  29. int isIntersect(LinkList list1, LinkList list2)  
  30. {  
  31.     LinkList ptr1 = list1->next;  
  32.     LinkList ptr2 = list2->next;  
  33.     int len1 = getLength(list1);  
  34.     int len2 = getLength(list2);  
  35.     int step = len1 - len2;  
  36.     int index;  
  37.     if(step > 0)             //list1长,那么list1先走step;  
  38.     {  
  39.         for (index = 0; index < step; index ++)  
  40.             ptr1 = ptr1->next;  
  41.     }  
  42.     else                    //list2长,那么list2先走step;  
  43.     {  
  44.         for (index = 0; index < -1 * step; index ++)  
  45.                     ptr2 = ptr2->next;  
  46.     }  
  47.     while (ptr1 != NULL)  
  48.     {  
  49.         if (ptr1 == ptr2)  
  50.             {  
  51.                 printf("the first intersection node is %d/n", ptr1->data);  
  52.                 return 1;  
  53.             }  
  54.         ptr1 = ptr1->next;  
  55.         ptr2 = ptr2->next;  
  56.     }  
  57.     printf("there is no insection node between the two list");  
  58.     return 0;  
  59. }  
  60. int main()  
  61. {  
  62. int a4[] = {1,2,3,4,5};  
  63.     LinkList list = CreatList(a4,5);  
  64.     LinkList current = list->next;  
  65.     while (current->next)  
  66.     {  
  67.         current = current->next;  
  68.     }  
  69.     current->next = list->next->next;   //公共点为4  
  70.     int result1 = isLoop(list);  
  71.         getLoopNode(list);  
  72. }