順序表的實現

/* Note:Your choice is C IDE */
#include "stdio.h"
#define INIT_SIZE 100
#define INCREMENT 10
typedef struct SqList {
 char *elem;
 int length;  //線性表的長度
 int listsize;  //當前分配的存儲量
} SqList;
void InitList_Sq (SqList *L) {
 L->elem=(char *) malloc (INIT_SIZE*sizeof (char));
 if (!L->elem) {
  printf ("/n Malloc Error /n");
  return;
 }  //存儲分配失敗
 L->length=0;  //空表的長度爲0
 L->listsize=INIT_SIZE;  //初始存儲容量
}  //InitList_Sq
void PrintList_Sq (SqList L) {
 int j;
 printf ("/nL( ");
 for (j=0; j<L.length; j++)
  printf ("%d ",*(L.elem+j));
 printf (")/n ");
}  //PrintList_Sq
void InsertList_Sq (SqList *L, int i, int e) {
 SqList new0;
 int j;
 if (i>L->length+1)  i=L->length+1;
 if (L->length>=L->listsize){ //當前存儲空間已滿,需增加容量
    
 new0.elem=(char *) realloc(L->elem,  (L->listsize+INCREMENT)*sizeof(char));
 if (!new0.elem) {
  printf ("/n Realloc Error /n");
  return;
 }  //存儲重分配失敗
 
 for (j=0; j<L->listsize; j++)  new0.elem[j]=L->elem[j];
    L->elem=new0.elem;  //新的基地址

 L->listsize += INCREMENT;  //增加存儲容量
 }
 if (i<=L->length)
  for (j=L->length; j>=i; --j) L->elem[j]=L->elem[j-1];
  //插入位置及其之後的數據元素右移一個位置
 L->elem[i-1]=e;  //插入數據元素e
 ++(L->length);  //線性表的長度增1
} //InsertList_Sq
DeleteList_Sq (SqList *L, int i) {
 int j;
 if (i<1 || i>L->length) {
  printf ("/n%d: Overflow./n",i);
  return;
 }
 if (L->length>0)
  for (j=i-1; j<L->length; ++j)
   L->elem[j]= L->elem[j+1];
   //被刪除元素之後的元素依次左移一位
 --(L->length);   //線性表的長度減1
}  //DeleteList_Sq
void main()
{
    SqList L;
    InitList_Sq(&L);
    InsertList_Sq(&L,1,10);
    InsertList_Sq(&L,2,20);
    InsertList_Sq(&L,3,30);
    PrintList_Sq(L);
    InsertList_Sq(&L,2,40);
    PrintList_Sq(L);
    DeleteList_Sq(&L,3);
    PrintList_Sq(L);
   
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章