ch2_stable.c

来自「本人讲授数据结构课程时的所写的示例程序」· C语言 代码 · 共 74 行

C
74
字号
/*
表的顺序实现(插入操作保持)
author: kk.h
date: 2006.9
http://www.cocoon.org.cn
*/

#include "stdio.h"
typedef struct{
  int no;
  int grade;
}ElemType;

typedef struct{
  ElemType *elem;
  int length;
  int listsize;
}SqList;

int InitList(SqList *pL)
{
  pL->listsize = 10;
  pL->elem = (ElemType*)malloc(pL->listsize*sizeof(ElemType));
  pL->length=0;
}
DestroyList(SqList *pL)
{
  free(pL->elem);
}
int ListInsert(SqList *pL,ElemType e)
{
  int i,j;
  if (pL->length>=pL->listsize){
    pL->listsize = pL->listsize + 10;
    pL->elem = (ElemType *)realloc(pL->elem,(pL->listsize)*sizeof(ElemType));
  }

  /*找插入点的位置*/
  for(i=0;i<pL->length;i++){
    if (e.grade>pL->elem[i].grade)
       break;
  }

  /*向后移动数据*/
  for(j=pL->length+1;j>i;j--)
    pL->elem[j]=pL->elem[j-1];

  pL->elem[i]=e;

  pL->length=pL->length+1;
  return 1;
}
ShowList(SqList*pL)
{
  int i;
  for(i=0;i<pL->length;i++){
    printf("\n(%d,%d)",pL->elem[i].no,pL->elem[i].grade);
  }  
}
main()
{
  SqList L;
  ElemType e;
  InitList(&L);
  e.no=1;e.grade=85;
  ListInsert(&L,e);
  ListInsert(&L,e);

  ShowList(&L);
  DestroyList(&L);

  getch();
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?