顺序表

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
#define Max_SeqList 10
 typedef struct{
  int num;
 }Student;
   
 typedef struct{
  Student * date;
  int Length;
     int ListLength;


 }SeqList;

 void InitList(SeqList* L){//1.初始化顺序表
  L->date=(Student *)malloc(Max_SeqList*sizeof(Student));
  if(!L->date)
  printf("内存分配失败 ");
  L->Length=0;
  L->ListLength=Max_SeqList;
  printf("顺序表创建成功 ");
 }
    
 void ClearList(SeqList *L){//2.清空顺序表
  L->Length=0;
    L->ListLength=0;
  printf("顺序表清除成功");
 }

 int isEmpty(SeqList *L){//3.判断顺序表是否为空
 
  if(L->Length==0) return 0;
 else
  return 1;
}

 int LengthList(SeqList *L){//4.顺序表的长度
 
 return L->ListLength;

}

    void TraverseList(SeqList *L){//5.遍历顺序表
 int i;
  for(i=0;i<L->Length;i++)
   printf("号码为:%d ",L->date[i]);
 }


 void InsertList(SeqList *L,int i,int e){//6.插入元素
  int k;
  if(L->Length==Max_SeqList) printf("顺序表已经满了");
  if(i<1||i>L->Length+1) printf("插入位置无效");
  for(k=L->Length-1;k>=i-1;k--)
   L->date[k+1]=L->date[k];
      L->date[i-1].num=e;
   L->Length++;
   printf("插入完成");
 }

 void DeleteList (SeqList *L,int i){//7.删除元素
   int k;
  if(L->Length==0) printf("顺序表已经满了");
  if(i<1||i>L->Length+1) printf("删除位置无效");
  //*e=L->date[i-1].num;
  for(k=i;k<=L->Length;k++){
     L->date[k-1]=L->date[k];
   L->Length--;
  }
}

 void LocateList(int e, SeqList *L){//8.查找元素
   int i=0;
   while(i<L->Length&&L->date[i].num!=e)
   i++;
  if(i<L->Length)
   printf("找到了,位置在%d",i+1);
  else
   printf("找不到");
}
 
 


int main(){
 
    int choice;
 int m=0;
    int n=0;
 int z=0;
 int j=0;
 SeqList *List;
 List=(SeqList*)malloc(sizeof(SeqList));
    while(1){
  printf("------------TEST------------ ");
  printf("1.初始化表 2.清空顺序表 3.判断顺序表是否为空 4.顺序表的长度 5.遍历顺序表 6.插入元素 7.删除元素 8.查找元素");
  printf("请选择:");
  scanf("%d",&choice);
  switch(choice){
      case 1:
     InitList(List);

    break;
      case 2:ClearList(List);break;
   case 3:
    if(isEmpty(List))
    printf("表不为空 ");
    else
    printf("表为空 ");
    break;
   case 4:printf("表的长度为%d",LengthList(List)); break;
   
   case 5: TraverseList(List); break;
   case 6:
    
    printf("输入插入位置 ");
    scanf("%d",&m);
    printf("输入插入值 ");
    scanf("%d",&n);
       InsertList(List,m,n);
             break;
   case 7:
    printf("输入你要删除的元素位置: ");
    scanf("%d",&z);
    DeleteList (List,z);
    printf("元素已删除");
    break;
   case 8:
    
    printf("请输入你要查找的元素:");
    scanf("%d",&j);
     LocateList(j, List);
    break;
   
  
  }

 }

 return 0;
}

原文地址:https://www.cnblogs.com/wantao/p/7828577.html