已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−表示序列的结尾(−不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL
。
输入样例:
1 3 5 -1 2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10
第一次做:
#include<stdio.h> #include<malloc.h> #include<stdlib.h> //函数状态码定义 #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef int ElemType; //假设线性表中的元素均为整型 typedef struct LNode { ElemType data; struct LNode *next; }LNode,*LinkList; //循环单链表类型定义与单链表定义相同,区别在尾节点next取值 LinkList Plus(LinkList l1, LinkList l2) { LinkList L; L = (LNode *)malloc(sizeof(LNode)); L->next = NULL; LNode *p = L; LNode *p1, *p2; p1 = l1->next; p2 = l2->next; while(p1!=NULL&&p2!=NULL){ if(p1->data<=p2->data){ p->next = p1; p = p1; p1 = p1->next; } else{ p->next = p2; p = p2; p2 = p2->next; } } if(p1 == NULL){ while(p2!=NULL){ p->next = p2; p = p2; p2 = p2->next; } } else{ while(p1!=NULL){ p->next = p1; p = p1; p1 = p1->next; } } return L; } int main() { LinkList L1; LinkList L2; LinkList L; LNode *p, *tem; L1 = (LNode *)malloc(sizeof(LNode)); L2 = (LNode *)malloc(sizeof(LNode)); p = (LNode *)malloc(sizeof(LNode)); L1->next = NULL; L2->next = NULL; int temp; p = L1; while(scanf("%d", &temp)!=EOF){ if(temp<0) break; else{ tem = (LNode *)malloc(sizeof(LNode)); tem->data = temp; tem->next = NULL; p->next = tem; p = tem; } } p = L2; while(scanf("%d", &temp)!=EOF){ if(temp<0) break; else{ tem = (LNode *)malloc(sizeof(LNode)); tem->data = temp; tem->next = NULL; p->next = tem; p = tem; } } L = Plus(L1, L2); p = L->next; if(p == NULL){ printf("NULL"); } else while(p!=NULL){ if(p->next != NULL){ printf("%d ", p->data); } else printf("%d", p->data); p = p->next; } } 1
第二次做:
#include<stdio.h> #include<stdlib.h> typedef struct LNode { int data; struct LNode* next; }LNode, *List; void CreatList(List &L) { LNode *p, *temp; L = (LNode* )malloc(sizeof(LNode)); p = L; int t; while(scanf("%d", &t)!=EOF){ if(t == -1) return ; temp = (LNode*)malloc(sizeof(LNode)); temp->next = NULL; temp->data = t; p->next = temp; p = temp; } } List Merge(List L1, List L2)//归并排序 { List L; L = (LNode*)malloc(sizeof(LNode)); L->next = NULL; LNode *p = L; L1 = L1->next; L2 = L2->next; while(L1!=NULL && L2!=NULL){ if(L1->data <= L2->data){ p->next = L1; p = L1; L1 = L1->next; } else{ p->next = L2; p = L2; L2 = L2->next; } } if(L1 != NULL) p->next = L1; if(L2 != NULL) p->next = L2; return L; } void CoutList(List L) { if(L->next == NULL){ printf("NULL"); return ; } L = L->next; while(L != NULL){ if(L->next != NULL) printf("%d ", L->data); else printf("%d", L->data); L = L->next; } } int main() { List L1, L2, L; CreatList(L1); CreatList(L2); L = Merge(L1, L2); CoutList(L); }