#include<stdio.h>
#include<malloc.h>
#define Null 0
typedef struct Node
{
int coeff;
int expo;
Node *next;
}listNode,*list;
list createList()
{
list head;
head = (list)malloc(sizeof(listNode));
head = NULL;
printf("want to create a new node?y/n\n");
char ch;
fflush(stdin);
scanf("%c",&ch);
while(ch=='Y' || ch== 'y')
{
list p;
p = (list)malloc(sizeof(listNode));
printf("input coeff\n");
int coeff;
scanf("%d",&coeff);
p->coeff = coeff;
printf("input expo\n");
int expo;
scanf("%d",&expo);
p->expo = expo;
p->next = NULL;
//链表为空的时候,即添加首个元素
if(head == NULL)
{
head=p;//添加代码
}
else
{
list prev,curr;
curr = head;
prev = NULL;
//找到添加位置
while(curr!=NULL && curr->expo>p->expo)
{
prev=curr;
curr=curr->next;//添加代码
}
if(curr!=NULL && curr->expo == p->expo)
{
curr->coeff = curr->coeff + p->coeff;
printf("want to create a new node?y/n\n");
fflush(stdin);
scanf("%c",&ch);
if(ch=='Y' || ch== 'y')
continue;
else
return head;
}
//插入结点,结点非首
if(prev != NULL)
{
p->next=curr;
prev->next=p;
//添加代码
}
//插入结点,结点为首
else
{
p->next=curr;
head=p;
//添加代码
}
}
printf("want to create a new node?y/n\n");
fflush(stdin);
scanf("%c",&ch);
}
return head;
}
list add(list head1,list head2)
{
list head,newNode,ptr1,ptr2,ptr3;
ptr1 = head1;
ptr2 = head2;
head = NULL;
while(ptr1 != NULL && ptr2 != NULL)
{
newNode = (list)malloc(sizeof(listNode));
if(ptr1->expo > ptr2->expo)
{
newNode->coeff = ptr1->coeff;
newNode->expo = ptr1->expo;
newNode->next = NULL;
ptr1 = ptr1->next;
}
else if(ptr1->expo < ptr2->expo)
{
newNode->coeff = ptr2->coeff;
newNode->expo = ptr2->expo;
newNode->next = NULL;
ptr2 = ptr2->next;//添加代码
}
else
{
newNode->coeff = ptr1->coeff + ptr2->coeff;
newNode->expo = ptr1->expo;
newNode->next = NULL;
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
if(head==NULL)
{
head = newNode;
}
else
{
ptr3 = head;
//添加代码
while(ptr3->next != NULL)
ptr3 = ptr3->next;
ptr3->next = newNode;
}
}
while(ptr1 != NULL)
{
newNode = (list)malloc(sizeof(listNode));
newNode->coeff = ptr1->coeff;
newNode->expo = ptr1->expo;
newNode->next = NULL;
ptr3 = head;
if(ptr3 == NULL)
head = ptr3 = newNode;
else
{
while(ptr3->next != NULL)
ptr3 = ptr3->next;
ptr3->next = newNode;//添加代码
}
ptr1 = ptr1->next;
}
while(ptr2 != NULL)
{
newNode = (list)malloc(sizeof(listNode));
newNode->coeff = ptr2->coeff;
newNode->expo = ptr2->expo;
ptr3 = head;
if(ptr3 == NULL)
head = ptr3 = newNode;
else
{
while(ptr3->next != NULL)
ptr3 = ptr3->next;
ptr3->next = newNode;
}
ptr2 = ptr2->next;
}
return head;
}
void display(list head)
{
list ptr = head;
while(ptr != NULL)
{
if(ptr != head )
printf("+");
printf("%d",ptr->coeff);
printf("x^");
printf("%d",ptr->expo);
ptr = ptr->next;
}
printf("\n");
}
int main(int argc, char* argv[])
{
list head,head1,head2;
printf("input the first list\n");
head1 = createList();
display(head1);
printf("input the second list\n");
head2 = createList();
display(head2);
head = add(head1,head2);
display(head);
return 0;
}
温馨提示:答案为网友推荐,仅供参考