数据结构上机2单链表合并 非递减
#include <stdio.h> #include <malloc.h> #define OK 1 #define OVERFLOW -1 #define ERROR 0 typedef int ElemType; typedef int Status; typedef struct LNode { ElemType data; struct LNode * next; } LNode, * LinkList; void Creatlist_L(LinkList * L, int n) { int i; LinkList p; *L = (LinkList)malloc(sizeof(LNode)); (*L)->next = NULL; for (i = n; i > 0; --i) { p = (LinkList)malloc(sizeof(LNode)); scanf("%d", &(p->data)); p->next = (*L)->next; (*L)->next = p; } } Status ListInsert_L(LinkList * L, int i, ElemType e) { LinkList p, s; int j; p = *L; j = 0; while (p && j < i - 1) { p = p->next; ++j; } if (!p || j > i - 1) return ERROR; s = (LinkList)malloc(sizeof(LNode)); s->data = e; s->next = p->next; p->next = s; return OK; } Status ListDelete_L(LinkList * L, int i, ElemType * e) { LinkList p, q; int j; p = *L; j = 0; while(p->next && j<i-1){ p = p->next; ++j; } if(!(p->next) || j>i-1) return ERROR; q = p->next; p->next = q->next; *e = q->data; free(q); return OK; } Status MergeList_L(LinkList * La, LinkList * Lb, LinkList *Lc) { LinkList pa, pb, pc; pa = (*La)->next; pb = (*Lb)->next; *Lc = pc = *La; while(pa&&pb){ if(pa->data <= pb->data){ pc->next = pa; pc = pa; pa = pa->next; }else{ pc->next = pb; pc = pb; pb = pb->next; } } pc->next = pa?pa:pb; free(*Lb); return OK; } void Print(LinkList L) { LinkList p; p = L->next; while (p) { printf("%d ", p->data); p = p->next; } printf("\n"); } int main(void) { LinkList la, lb, lc; int i; ElemType e; printf("\n-----------MergeList------------\n"); Creatlist_L(&la, 3); printf(" The la:"); Print(la); Creatlist_L(&lb, 3); printf(" The lb:"); Print(lb); MergeList_L(&la, &lb, &lc); printf(" The lc:"); Print(lc); printf("\n--------INSERT-----------------\n"); printf("请输入要插入的位置:"); scanf("%d", &i); printf("请输入要插入的数据:"); scanf("%d", &e); if(ListInsert_L(&lc, i, e) != OK) printf("插入失败\n"); printf("The values of LinkList:\n"); Print(lc); printf("\n---------DELETE---------------\n"); printf("请输入要删除的位置:"); scanf("%d", &i); if(ListDelete_L(&lc, i, &e) != OK) printf("删除失败\n"); printf("The values of LinkList:\n"); Print(lc); return 0; }
本文来自博客园,作者:一支小白,转载请注明原文链接:https://www.cnblogs.com/startnow/p/5052595.html