马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdlib.h>
typedef struct Node *node;
struct Node
{
int x;
int z;
node next;
};
node read();
void print(node lsit);
node he(node list1,node list2);
node ji(node list1,node list2);
void freeList(node head);
node read()
{
int i;
scanf("%d",&i);
node head = (node)malloc(sizeof(node));
head->next = NULL;
node p = head;
while(i--)
{
node temp = (node)malloc(sizeof(node));
scanf("%d %d",&temp->x,&temp->z);
p->next = temp;
p = p->next;
}
p->next = NULL;
return head;
}
node he(node list1,node list2)
{
node temp;
node head = (node)malloc(sizeof(struct Node));
head->next = NULL;
node p = head;
if(list2->next == NULL)
return list1;
else
{
list1 = list1->next;
list2 = list2->next;
while(list1 && list2)
{
temp = (node)malloc(sizeof(struct Node));
if(list1->z == list2->z)
{
temp->x = list1->x + list2->x;
temp->z = list1->z;
list1 = list1->next;
list2 = list2->next;
}
else if(list1->z > list2->z)
{
temp->x = list1->x;
temp->z = list1->z;
list1 = list1->next;
}
else
{
temp->x = list2->x;
temp->z = list2->z;
list2 = list2->next;
}
p->next = temp;
p = p->next;
}
for(;list1;list1 = list1->next)temp = (node)malloc(sizeof(struct Node)),temp->x = list1->x,temp->z = list1->z,p->next = temp,p = p->next;
for(;list2;list2 = list2->next)temp = (node)malloc(sizeof(struct Node)),temp->x = list2->x,temp->z = list2->z,p->next = temp,p = p->next;
p->next = NULL;
return head;
}
}
node ji(node list1,node list2)
{
node t,L = (node)malloc(sizeof(struct Node));
L->next = NULL;
list1 = list1->next;
list2 = list2->next;
for(list1;list1;list1=list1->next)
{
node temp;
node head = (node)malloc(sizeof(struct Node));
head->next = NULL;
node p = head;
for(t = list2;t;t=t->next)
{
temp = (node)malloc(sizeof(struct Node));
temp->x = list1->x * t->x;
temp->z = list1->z + t->z;
p->next = temp;
p = p->next;
}
p->next = NULL;
L = he(head,L);
freeList(head);//这里head创造的链表传入到he函数里了并返回了新的一个链表,所以可以free掉head了吗?
}
//L->next = NULL;
return L;
}
void print(node list)
{
if(list->next)
{
list = list->next;
while(list)
{
printf("%d %d",list->x,list->z);
list = list->next;
if(list)
printf(" ");
}
}
else
printf("0 0");
}
void freeList(node head)
{
node temp;
while (head != NULL)
{
temp = head;
head = head->next;
free(temp);
}
}
int main()
{
node list1,list2;
list1 = read();
list2 = read();
// print(list1);
// print(list2);
print(ji(list1,list2));
printf("\n");
print(he(list1,list2));
freeList(list1);
freeList(list2);
return 0;
}
L = he(head,L);
freeList(head);
这里在ji函数里头结点head创造的链表传入到he函数里了并返回了新的一个链表头结点L,所以可以free掉head了吗,因为马上head又要重置,创建出一个新的链表 但是free掉为什么会影响答案结果? |