三木社区

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 316|回复: 0

C语言数据结构-algo2-3.c

[复制链接]

1562

主题

1564

帖子

4904

积分

博士

Rank: 8Rank: 8

积分
4904
发表于 2017-9-1 07:50:08 | 显示全部楼层 |阅读模式
  1. /* algo2-3.c 实现算法2.7的程序 */
  2. #include"c1.h"
  3. typedef int ElemType;
  4. #include"c2-1.h"
  5. #include"bo2-1.c"

  6. void MergeList(SqList La,SqList Lb,SqList *Lc) /* 算法2.7 */
  7. { /* 已知顺序线性表La和Lb的元素按值非递减排列。 */
  8.    /* 归并La和Lb得到新的顺序线性表Lc,Lc的元素也按值非递减排列 */
  9.    ElemType *pa,*pa_last,*pb,*pb_last,*pc;
  10.    pa=La.elem;
  11.    pb=Lb.elem;
  12.    (*Lc).listsize=(*Lc).length=La.length+Lb.length;/*不用InitList()创建空表Lc */
  13.    pc=(*Lc).elem=(ElemType *)malloc((*Lc).listsize*sizeof(ElemType));
  14.    if(!(*Lc).elem) /* 存储分配失败 */
  15.      exit(OVERFLOW);
  16.    pa_last=La.elem+La.length-1;
  17.    pb_last=Lb.elem+Lb.length-1;
  18.    while(pa<=pa_last&&pb<=pb_last) /* 表La和表Lb均非空 */
  19.    { /* 归并 */
  20.      if(*pa<=*pb)
  21.        *pc++=*pa++;
  22.      else
  23.        *pc++=*pb++;
  24.    }
  25.    while(pa<=pa_last) /* 表La非空且表Lb空 */
  26.      *pc++=*pa++; /* 插入La的剩余元素 */
  27.    while(pb<=pb_last) /* 表Lb非空且表La空 */
  28.      *pc++=*pb++; /* 插入Lb的剩余元素 */
  29. }

  30. void print(ElemType *c)
  31. {
  32.    printf("%d ",*c);
  33. }

  34. void main()
  35. {
  36.    SqList La,Lb,Lc;
  37.    int j;
  38.    InitList(&La); /* 创建空表La */
  39.    for(j=1;j<=5;j++) /* 在表La中插入5个元素 */
  40.      ListInsert(&La,j,j);
  41.    printf("La= "); /* 输出表La的内容 */
  42.    ListTraverse(La,print);
  43.    InitList(&Lb); /* 创建空表Lb */
  44.    for(j=1;j<=5;j++) /* 在表Lb中插入5个元素 */
  45.      ListInsert(&Lb,j,2*j);
  46.    printf("Lb= "); /* 输出表Lb的内容 */
  47.    ListTraverse(Lb,print);
  48.    MergeList(La,Lb,&Lc);
  49.    printf("Lc= "); /* 输出表Lc的内容 */
  50.    ListTraverse(Lc,print);
  51. }
复制代码


回复

使用道具 举报

Archiver|手机版|小黑屋|三木电子社区 ( 辽ICP备11000133号-4 )

辽公网安备 21021702000620号

GMT+8, 2025-11-18 19:03 , Processed in 0.027644 second(s), 23 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表