#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct Node
{
char name[128] ;
int month;
int income; //收入
int expenditure;//支出
int save;//結餘
struct Node *next ;
};
struct Node *head1 = NULL, *head2= NULL, *head3= NULL;
struct Node *create_head(struct Node *new_node,struct Node *head)
{
head = (struct Node *) calloc(1,sizeof(struct Node));
memcpy(head,new_node,sizeof(struct Node));
return head;
}
struct Node *add_node(struct Node *new_node,struct Node *head)
{
struct Node *ptr;
ptr = (struct Node *) calloc(1,sizeof(struct Node));
memcpy(ptr,new_node,sizeof(struct Node));
ptr->next = head;
head = ptr;
return head;
}
struct Node* create_link_list(FILE *fd,struct Node *head)
{
struct Node new_node = {0};
while(4 == fscanf(fd,"%s %d %d %d",new_node.name,&new;_node.month \
, &new;_node.expenditure, &new;_node.income)){
if(new_node.month > 12 || new_node.month < 1)
continue;
new_node.next = NULL;
if( head != NULL)
head = add_node(&new;_node,head);
else
head = create_head(&new;_node,head);
}
return head;
}
struct Node* insert_node(struct Node *new_node_ptr,struct Node *head)
{
struct Node *head_ptr;
head_ptr = head;
if(head == NULL) //list 為空
head = new_node_ptr;
// 插入在 List 的開頭
else if(new_node_ptr->month < head_ptr->month && new_node_ptr->month > 0){
new_node_ptr->next = head;
head = new_node_ptr;
}else{
while(head_ptr != NULL){
if(head_ptr->month == new_node_ptr->month){ //重覆的月份
free(new_node_ptr);
head_ptr = NULL;
}
// 插入在 List 的最尾端
else if(head_ptr->next == NULL && new_node_ptr->month > head_ptr->month){
head_ptr->next = new_node_ptr;
new_node_ptr->next = NULL;
head_ptr = NULL;
}
// 插入在 List 的中間
else if(head_ptr->month < new_node_ptr->month \
&& head_ptr->next->month > new_node_ptr->month){
new_node_ptr->next = head_ptr->next;
head_ptr->next = new_node_ptr;
head_ptr = NULL;
}else
head_ptr = head_ptr->next;
}
}
return head;
}
int main(int argc,char *argv[])
{
FILE *fd1, *fd2 ;
int balance = 0;
struct Node *ptr;
fd1 = fopen("exam1.txt","r");
if(fd1 < 0){
printf("Open File Error!\n");
return -1;
}
fd2 = fopen("exam2.txt","r");
if(fd2 < 0){
printf("Open File Error!\n");
return -1;
}
//create two list
head1 = create_link_list(fd1,head1);
head2 = create_link_list(fd2,head2);
// 合併兩個List
while(head1!=NULL){
ptr = head1;
head1 = head1->next;
ptr->next = NULL;
head3 = insert_node(ptr,head3);
}
while(head2!=NULL){
ptr = head2;
head2 = head2->next;
ptr->next = NULL;
head3 = insert_node(ptr,head3);
}
printf("姓名\t月份\t支出\t收入\t結餘\n");
while(head3!=NULL){
balance += (head3->income - head3->expenditure);
printf("%s\t%d\t%d\t%d\t%d\n",head3->name,head3->month , \
head3->expenditure, head3->income ,balance);
ptr = head3;
head3 = head3->next;
free(ptr);
}
fclose(fd1);
fclose(fd2);
return 0;
}Add a code snippet to your website: www.paste.org