編程實現順序表的基本操作

  1. void InitList(SqList &L)//建立空順序表函數
  2. voidListInsert(SqList &L, int i, ElemType e) //在順序表中第i個位置插入元素函數e 

  3. void ListDelete(SqList &L, int i, ElemType &e)//刪除順序表L的第i個數據元素,並用e返回其值。

  4.  void PrintList(SqList L)     // 輸出順序表函數 

  5.  int Locate(SqList L, ElemType e)  //若順序表L中存在數據元素e,則返回e在順序表L中第一次出現的位序;否則返回0.

  6. int ListLength(SqList L)    //求順序表L的表長

// 1.編程實現順序表的基本操作
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define LIST_INIT_SIZE 10 // 存儲空間的初始分配量
#define LISTINCREMENT 10 // 分配增量
typedef int ElemType; // 順序表中存放的是整數
typedef struct{
ElemType *elem; // 存儲空間基址
int length; // 當前長度
int listsize; // 當前分配的存儲容量
}SqList;

void InitList(SqList &L){
// 建立一個空的順序表L
L.elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if(L.elem){
L.length = 0;
L.listsize = LIST_INIT_SIZE;
}
}

void CreateSqList(SqList &L,int m){
// 初始條件:順序表L已存在
// 操作結果:將m個元素依次加入順序表L
int i;
for(i = 0;i < m;i++){
scanf("%d",&L.elem[i]);
L.length++;
if(L.length >= L.listsize){
L.elem = (ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
L.listsize += LISTINCREMENT;
}
}
}

void ListInsert(SqList &L, int i, ElemType e){
// 初始條件:順序表L已存在,1<=i<=ListLength(L)+1
// 操作結果:在順序表L中第i個位置之前插入新的數據元素e,表長加1
ElemType *p,*q;
if(i<1||i>L.length+1)
exit(-2);
if(L.length >= L.listsize){
L.elem = (ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
L.listsize += LISTINCREMENT;
}
q = &(L.elem[i-1]);
for(p = &(L.elem[L.length-1]);p >= q;--p)
*(p+1) = *p;
*q = e;
++L.length;
}

void ListDelete(SqList &L, int i, ElemType &e){
// 初始條件:順序表L已存在,1<=i<=ListLength(L)
// 操作結果:刪除順序表L的第i個數據元素,並用e返回其值
ElemType *p;
if(i<1||i>L.length)
exit(-2);
e = L.elem[i-1];
for(p = &L.elem[i-1];p <= &L.elem[L.length-1];p++)
*(p-1) = *p;
--L.length;
}

void PrintList(SqList L){
// 初始條件:順序表L已存在
// 操作結果:打印順序表
int i;
for(i = 0;i < L.length;i++)
printf("%d ",L.elem[i]);
}

int Locate(SqList L, ElemType e){
// 初始條件:順序表L已存在
// 操作結果:若順序表L中存在數據元素e,則返回e在順序表L中第一次出現的位序;否則返回0
int i,result = 0;
for(i = 0;i < L.length;i++){
if(L.elem[i] == e){
result = i+1;
break;
}
}
return result;
}

int ListLength(SqList L){
// 初始條件:順序表L已存在
// 操作結果:返回順序表L的表長
return L.length;
}

int main(){
SqList L;
int n,i;
ElemType e;
InitList(L);
printf("請輸入表長:");
scanf("%d",&n);
printf("請輸入元素(空格分隔):");
CreateSqList(L,n);
printf("順序表爲:");
PrintList(L);
printf("\n");
printf("輸入插入位置和元素(空格分隔):");
scanf("%d %d",&i,&e);
ListInsert(L,i,e);
printf("順序表爲:");
PrintList(L);
printf("\n");
printf("輸入刪除位置:");
scanf("%d",&i);
ListDelete(L,i,e);
printf("刪除元素爲:%d\n",e);
printf("輸入待查找元素:");
scanf("%d",&e);
printf("查找結果:%d\n",Locate(L,e));
printf("順序表表長:%d\n",ListLength(L));
printf("按任意鍵結束...\n");
char ch = getch();
return 0;
}


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