代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct stuInfo {
char stuName[10]; /*学生姓名*/
int Age; /*年龄*/
} ElemType;
typedef struct node {
ElemType data;
struct node *next;
} ListNode, *ListPtr;
ListPtr List_Init();
void List_Insert(ListPtr h, ElemType x, char ch);
void List_Destroy(ListPtr h);
ListPtr List_Merge(ListPtr La, ListPtr Lb);
void OutPut(ListPtr La);
ListPtr List_Init() {
ListPtr p;
p = (ListPtr)malloc(sizeof(ListNode));
if (p == NULL) {
exit(0);
};
p->next = NULL;
return p;
}
void List_Destroy(ListPtr h) {
ListPtr cur = h->next;
for (; cur != NULL; h = cur, cur = cur->next) {
free(h);
}
free(h);
h = NULL;
}
void List_Insert(ListPtr h, ElemType x, char ch) {//ch为'<'则是按从小到大顺序插,'>'则相反
ListPtr newNode, pre, cur;
newNode = (ListPtr)malloc(sizeof(ListNode));
if (newNode == NULL) {
exit(0);
;
}
newNode->data.Age = x.Age;
strcpy(newNode->data.stuName, x.stuName);
pre = h;
cur = h->next;
if (ch == '>') {
for (; cur != NULL && newNode->data.Age < cur->data.Age;
pre = cur, cur = cur->next)
;
} else if (ch == '<') {
for (; cur != NULL && newNode->data.Age > cur->data.Age;
pre = cur, cur = cur->next)
;
}
else{
return;
}
if (cur == NULL) {
pre->next = newNode;
newNode->next = cur;
return;
}
if (newNode->data.Age == cur->data.Age) {//删去相同信息的项
if (strcmp(newNode->data.stuName, cur->data.stuName) == 0) {
return;
}
}
pre->next = newNode;
newNode->next = cur;
}
ListPtr List_Merge(ListPtr La, ListPtr Lb) {
ListPtr Lc, p;
Lc = List_Init();
for (p = La->next; p != NULL; p = p->next) {
List_Insert(Lc, p->data, '>');
}
for (p = Lb->next; p != NULL; p = p->next) {
List_Insert(Lc, p->data, '>');
}
return Lc;
}
void OutPut(ListPtr La) {
ListPtr p;
p = La->next;
printf("Name\tAge\n");
while (p != NULL) {
printf("%s\t%d\n", p->data.stuName, p->data.Age);
p = p->next;
}
printf("\n");
}
int main(void) {
ListPtr pHeadA, pHeadB, pHeadC;
FILE *inFile;
ElemType stu;
pHeadA = List_Init();
pHeadB = List_Init();
inFile = fopen("StuInfoA.txt", "r");
if (inFile == NULL) {
return 1;
}
while (!feof(inFile)) {
fscanf(inFile, "%s\t%d", stu.stuName, &stu.Age);
List_Insert(pHeadA, stu, '<');
fgetc(inFile);
}
inFile = fopen("StuInfoB.txt", "r");
if (inFile == NULL) {
return 1;
}
while (!feof(inFile)) {
fscanf(inFile, "%s\t%d", stu.stuName, &stu.Age);
List_Insert(pHeadB, stu, '<');
fgetc(inFile);
}
fclose(inFile);
pHeadC = List_Merge(pHeadA, pHeadB);
if (pHeadC == NULL) {
return 1;
};
printf("ListA\n");
OutPut(pHeadA);
printf("ListB\n");
OutPut(pHeadB);
printf("ListC\n");
OutPut(pHeadC);
List_Destroy(pHeadA);
List_Destroy(pHeadB);
List_Destroy(pHeadC);
getchar();
return 0;
}
文本
fghfg 45
bhkjh 98
dsfjgh 12
dfg 5
dfgrdg 77
fdgsdf 9
ftujh 87
wouero 9
dfg 5
wtwu 8
vbvxcv 66
dsfghk 18
网友评论