[作业]两个有序表合并为一个有序表
#include "stdio.h"
#include "malloc.h"
typedef struct LNode {
int data;
struct LNode *next;
}LNode, *LinkList;
LNode* InitLList_step(int low, int up,int step) {
LNode *head, *s, *r;
head = (LNode *)malloc(sizeof(LNode));
r = (LNode *)malloc(sizeof(LNode));
head->data = 9527;
head->next = r;
r->data = low;
r->next = NULL;
for (int i = low + step; i <= up;) {
s = (LNode *)malloc(sizeof(LNode));
s->data = i;
s->next = r->next;
r->next = s;
r = s;
i=i + step;
}
return head;
}
void PrintLList(LNode* l) {
LNode* s;
s = l->next;
while (s) {
printf("%d\t", s->data);
s = s->next;
}printf("\n");
}
LNode* MergeLList(LNode* l1, LNode* l2) {
LNode *head, *s, *r;
LNode* s1, *s2;
head = (LNode *)malloc(sizeof(LNode));
r = (LNode *)malloc(sizeof(LNode));
head->data = 9527;
head->next = r;
s1 = l1->next;
s2 = l2->next;
if (s1->data < s2->data){
r->data = s1->data;
r->next = NULL;
s1 = s1->next;
}else {
r->data = s2->data;
r->next = NULL;
s2 = s2->next;
}
while (s1 && s2) {
if (s1->data < s2->data){
s = (LNode *)malloc(sizeof(LNode));
s->data = s1->data;
s->next = r->next;
r->next = s;
r = s;
s1 = s1->next;
}else {
s = (LNode *)malloc(sizeof(LNode));
s->data = s2->data;
s->next = r->next;
r->next = s;
r = s;
s2 = s2->next;
}
}
if (s1){ s->next = s1; }
else { s->next = s2; }
return head;
}
int main() {
LNode* L1,*L2,*LL;
printf("创建顺序链表: \n");
L1 = InitLList_step(1, 10, 2);
PrintLList(L1);
L2 = InitLList_step(2, 20, 4);
PrintLList(L2);
printf("合并顺序链表: \n");
LL = MergeLList(L1, L2);
PrintLList(LL);
}