c语言问题,补全一下这个代码,确定两个列表中有多少元素是相同的

c语言问题,补全一下这个代码,确定两个列表中有多少元素是相同的

问题描述:

img
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

struct node {
struct node *next;
int data;
};

int intersection_size(struct node *head1, struct node *head2);
struct node *strings_to_list(int len, char *strings[]);

// DO NOT CHANGE THIS MAIN FUNCTION
int main(int argc, char *argv[]) {
// create two linked lists from command line arguments
int dash_arg = argc - 1;
while (dash_arg > 0 && strcmp(argv[dash_arg], "-") != 0) {
dash_arg = dash_arg - 1;
}
struct node *head1 = strings_to_list(dash_arg - 1, &argv[1]);
struct node *head2 = strings_to_list(argc - dash_arg - 1, &argv[dash_arg + 1]);

int result = intersection_size(head1, head2);
printf("%d\n", result);

return 0;

}

// return the number of values which occur in both linked lists
// no value is repeated in either list
int intersection_size(struct node *head1, struct node *head2) {

// PUT YOUR CODE HERE (change the next line!)
return 42;

}

// DO NOT CHANGE THIS FUNCTION
// create linked list from array of strings
struct node *strings_to_list(int len, char *strings[]) {
struct node *head = NULL;
for (int i = len - 1; i >= 0; i = i - 1) {
struct node *n = malloc(sizeof (struct node));
assert(n != NULL);
n->next = head;
n->data = atoi(strings[i]);
head = n;
}
return head;
}

int intersection_size(struct node *head1, struct node *head2) 
{
    if(head1 == NULL || head2==NULL)
        return 0;
     int nCount = 0;
    struct node *p = head1;
    while(p != NULL)
    {
          struct node *q = head2;
          while(q != NULL)
          {
              if(p->data == q->data)
                  nCount++;
              q = q->next;
          }
          p = p->next;
    }
    return nCount;
}

讲一下你的初步思路?

int intersection_size(struct node *head1, struct node *head2)
{
    if(head1 == NULL || head2 == NULL) return 0;

    int same = 0;

    struct node *p2;
    struct node *h, *has  = malloc(sizeof(struct node));//记录已经匹配过的相同元素
    assert(has != NULL);
    has->next = NULL;
    int ishave = 0;

    while(head1 != NULL)
    {
        p2 = head2;
        while(p2 != NULL)
        {
            ishave = 0;
            if(head1->data == p2->data)
            {
                h = has;
                while(h != NULL)    //查找该元素是否已经匹配过
                {
                    if(head1->data == h->data)
                    {
                        ishave = 1;
                        break;
                    }
                    h = h->next;
                }
                if(ishave)break;//已经匹配过的不进行重复记录
                
                struct node *n  = malloc(sizeof(struct node));
                assert(n != NULL);
                n->next = has;
                n->data = head1->data;
                has = n;

                same++;
            }

            p2 = p2->next;
        }

        head1 = head1->next;
    }

    // PUT YOUR CODE HERE (change the next line!)
    return same;
}

img