程序代码:
#include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct Node *PtrToNode; struct Node { ElementType Data; PtrToNode Next; }; typedef PtrToNode List; List Read(); /* 细节在此不表 */ void Print( List L ); /* 细节在此不表;空链表将输出NULL */ List Merge( List L1, List L2 ); List FreeList(List L); //用于链表释放 List Paixu(List L); //用于链表排序 int main() { List L1, L2, L; L1 = Read(); L2 = Read(); L = Merge(L1, L2); L1 = FreeList(L1); //释放L1 L2 = FreeList(L2); //释放L2 Print(L); Print(L1); Print(L2); return 0; } /* 你的代码将被嵌在这里 */ List Read() { PtrToNode first = NULL; int n; for (;;) { printf("Enter a series of integers (0 to terminate): "); scanf("%d", &n); if (n == 0)//当输入为0则退出循环 break; PtrToNode new_node = malloc(sizeof(struct Node)); if (new_node == NULL) { printf("Error: malloc failed in add to list\n"); exit(0); } new_node->Data = n; new_node->Next = first; first = new_node; } return Paixu(first); } void Print(List L) { List p; if (L==NULL) printf("NULL\n"); else { for (p = L; p != NULL; p = p->Next) printf("%d ", p->Data); printf("\n"); } } List Merge(List L1, List L2) { //合并链表 PtrToNode first = NULL; while (L1 != NULL)//创建并把旧链表复制到新链表 { PtrToNode new_node = malloc(sizeof(struct Node)); if (new_node == NULL) { printf("Error: malloc failed in add to list\n"); exit(0); } new_node->Data = L1->Data; new_node->Next = first; first = new_node; L1 = L1->Next; } while (L2 != NULL)//创建并把旧链表复制到新链表 { PtrToNode new_node = malloc(sizeof(struct Node)); if (new_node == NULL) { printf("Error: malloc failed in add to list\n"); exit(0); } new_node->Data = L2->Data; new_node->Next = first; first = new_node; L2 = L2->Next; } return Paixu(first); } List Paixu(List L)//链表排序 升序,只交换 Data { int n; PtrToNode first = L, t; for (t = first; t->Next != NULL;) { if (t->Data > (t->Next)->Data) { n = t->Data; t->Data = (t->Next)->Data; (t->Next)->Data = n; t = first; } else { t = t->Next; } } return first; } List FreeList(List L) { for (List t; L != NULL;) { t = L; L = L->Next; free(t); } return NULL; }
[此贴子已经被作者于2017-9-22 20:34编辑过]