#include <stdio.h>
#include <malloc.h>//构造结构体typedef struct list{int data;struct list next;}List,LNode;//函数声明List init_list(List head,int num);void print_list(List head);List merge(List l1,List l2);void main(){ List l,l1,l2; l1 = (LNode)malloc(sizeof(LNode)); l1 = init_list(l1,3); l2 = (LNode)malloc(sizeof(LNode)); l2 = init_list(l2,7); l = merge(l1,l2); print_list(l);}//两个有序链表合并函数/List merge(List l1,List l2){ List head,p,s; head = (List)malloc(sizeof(LNode)); p = head; while(l1 != NULL && l2 != NULL) { s = (List)malloc(sizeof(LNode)); if(l1->data > l2->data) { s ->data = l2->data; l2 = l2->next; }else{ s ->data = l1->data; l1 = l1->next; } s->next = NULL; p->next = s; p = p->next; } while(l1 != NULL) { s = (List)malloc(sizeof(LNode)); s->data = l1->data; l1 = l1->next; s->next = NULL; p->next = s; p = p->next; } while(l2 != NULL) { s = (List)malloc(sizeof(LNode)); s->data = l2->data; l2 = l2->next; s->next = NULL; p->next = s; p = p->next; } return head->next;}///两个有序链表合并函数优化List merge(List l1,List l2){ List head,p,s; head = (List)malloc(sizeof(LNode)); p = head; while(l1 != NULL || l2 != NULL) { s = (List)malloc(sizeof(LNode)); if(l1 != NULL && l1->data <= l2->data) { s ->data = l1->data; l1 = l1->next; }else{ s ->data = l2->data; l2 = l2->next; } s->next = NULL; p->next = s; p = p->next; } return head->next;}//链表初始化函数List init_list(List head,int num){ int i = 1; List p = head; while(i <= num) { List s; s = (LNode*)malloc(sizeof(LNode)); s->data = i * num; s->next = NULL; p->next = s; p = p->next; i++; } return head->next;}//链表输出函数void print_list(List head){ List p; p = head; while(p != NULL) { printf("%d “,p->data); p = p->next; } printf(”\n");}
|