链接列表的交集

时间:2015-07-27 16:14:16

标签: c data-structures linked-list

我编写了一个程序来查找两个链接列表的交集(公共元素),但它无法正常工作。我认为 intersect()函数中的while循环存在一些问题。如果有人能向我解释错误,我将非常感激。

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node{
    int data;
    struct node *next;
}; struct node *nw, *head, *tail, *temp;

struct node1{
    int data1;
    struct node1 *next1;
}; struct node1 *nw1, *head1, *tail1, *temp1;

struct node2{
    int data2;
    struct node2 *next2;
}; struct node2 *nw2, *head2, *tail2, *temp2, *t;

void intersect(){
    printf("\nINTERSECTION OF LINKED LIST \n");
    temp=head;
    temp1=head1;
    while(temp->next!=NULL && temp1->next1!=NULL)
    {
        temp->next=head;
        while(temp->data != temp1->data1 && temp->next!=NULL)
        {
                temp=temp->next;  
/* PROBLEM is with this loop it doesnt increment and hence become infinte. */
    }

        if(temp->data == temp1->data1)
        {
            printf("Common Element : %d\t", temp1->data1);
        }
    }
}
int main(){
    int n,i,item,item1;

    printf("Enter the number of nodes of 1st  Linked List");
    scanf("%d", &n);
    nw=(struct node *)malloc(sizeof(struct node));
    nw->data=NULL;
    nw->next=NULL;
    head=nw;
    tail=nw;
    for(i=0;i<n;i++){
        printf("Enter the item ");
        scanf("%d", &item);
        if(head->data==NULL)
            head->data=item;
        else{
            nw=(struct node *)malloc(sizeof(struct node));
            nw->data=item;
            nw->next=NULL;
            tail->next=nw;
            tail=nw;
        }
    }

    printf("Enter the number of nodes for second LL");
    scanf("%d", &n);
    nw1=(struct node1 *)malloc(sizeof(struct node1));
    nw1->data1=NULL;
    nw1->next1=NULL;
    head1=nw1;
    tail1=nw1;
    for(i=0;i<n;i++){
        printf("Enter the item ");
        scanf("%d", &item1);
        if(head1->data1==NULL)
            head1->data1=item1;
        else{
            nw1=(struct node1 *)malloc(sizeof(struct node1));
            nw1->data1=item1;
            nw1->next1=NULL;
            tail1->next1=nw1;
            tail1=nw1;
        }
    }
        temp=head;
        while(temp!=NULL){
            printf("%d    ", temp->data);
            temp=temp->next;
        }
        printf("\n\n\n\n\n");
        temp1=head1;
        while(temp1!=NULL){
            printf("%d    ", temp1->data1);
            temp1=temp1->next1;
        }

        intersect();
        getch();
}

1 个答案:

答案 0 :(得分:1)

您需要一个嵌套的for / while循环来查找所有常用项。以下代码中的某些内容应该有效。

void intersect(){
   printf("\nINTERSECTION OF LINKED LIST \n");
   temp=head;
   temp1=head1;

   for ( ; temp != NULL; temp = temp->next )
   {
      for ( temp1 = head1; temp1 != NULL; temp1 = temp1->next )
      {
         if(temp->data == temp1->data1)
         {
            printf("Common Element : %d\t", temp1->data1);
         }
      }
   }
}
相关问题