在我的代码中,我必须比较两个列表,其中一个应该是动态数组,另一个应该是链接列表。所以我写了这样的东西; 特别是我不确定此功能
node * insert(node *head, int num){
node *new = (node *) malloc(sizeof(node));
new->data = num;
new->next = NULL;
//if head is null execute
if (head == NULL){
head = new;
}
else{
node *current = head;
while (current->next != NULL){
current = current->next;
}
current->next = new;
}
return head;
}
我的整个代码如下
#include <stdio.h>
#include <stdlib.h>
typedef struct nodes {
int data;
struct nodes * next;
}node;
typedef struct differents{
int n1,n2;
}different;
node * insert(node *head, int num);
different * compare(node *head, int * arr,int counter, int *count_dif);
void print_arr(int *arr,int counter);
void print_linked(node *head);
int main(){
int *arr,*temp;
node *head=NULL;
int counter=1,input,count_dif;
different *dif;
arr=(int*)malloc(sizeof(int));
printf("'0' for stop entering new number\n");
while (input !=0){
printf("Input:");
scanf(" %d",&input);
arr[counter-1]=input;
counter++;
temp=arr;
arr=(int*)calloc(counter,sizeof(int));
for (int i=0; i<counter-1; i++) arr[i]=temp[i];
free(temp);
}
counter-=2;
printf("You are entered %d num for the first list\nEnter %d num for the second list\n",counter,counter );
for (int i=0; i<counter; i++){
printf("Input:");
scanf(" %d",&input);
head=insert(head,input);
}
print_arr(arr,counter);
print_linked(head);
node *temp_head=head;
dif=compare(temp_head,arr,counter,&count_dif);
printf("There are %d different num in the lists\nThey are\nIn first list\tIn second list\n",count_dif );
for (int i=0; i<count_dif; i++){
printf("\t%d\t\t",dif[i].n1 );
printf("%d\n",dif[i].n2 );
}
}
node * insert(node *head, int num){
node *new = (node *) malloc(sizeof(node));
new->data = num;
new->next = NULL;
//if head is null execute
if (head == NULL){
head = new;
}
else{
node *current = head;
while (current->next != NULL){
current = current->next;
}
current->next = new;
}
return head;
}
different * compare(node *head, int * arr,int counter, int *count_dif){
different *dif,*temp;
int diff_num=1;
for (int i=0; i<counter; i++){
if (arr[i]!=head->data){
temp=dif;
dif=(different*)calloc(diff_num,sizeof(different));
for (int j=0; j<diff_num; j++) dif[j]=temp[j];
dif[diff_num-1].n1=arr[i];
dif[diff_num-1].n2=head->data;
if (temp!=NULL) free(temp);
diff_num++;
}
head=head->next;
}
*count_dif=diff_num-1;
return dif;
}
void print_arr(int *arr,int counter){
printf("first list:{ ");
for (int i=0; i<counter; i++) printf("%d ",arr[i] );
printf("}\n");
}
void print_linked(node *head){
printf("second list:{ ");
node *print=head;
while(print){
printf("%d ",print->data );
print=print->next;
}printf("}\n");
}
输入
5 4 6 3 0
5 2 4 3
预期输出
first list:{ 5 4 6 3 }
second list:{ 5 2 4 3 }
There are 3 different num in the lists
They are
In first list In second list
7 5
8 7
输出值
first list:{ 5 4 6 3 }
second list:{ 5 2 4 3 }
There are 2 different num in the lists
They are
In first list In second list
4 2
6 -281779616
如果我输入的数字超过6或7,则可以正常工作,但是输入的数字很少,则可以给我带来垃圾值。