#include <bits/stdc++.h>
#include<stdio.h>
#define MaxSize 1000
using namespace std;
typedef int ElemType;
type struct {
ElemType data[MaxSize];
ElemType length;
}SqList;
//初始化线性表
void InitList(SqList *&L){
L = (SqList*)malloc(sizeof(SqList)*MaxSize);
L->length = 10;
}
//线性表长度
int Length(SqList* L){
return L->length;
}
//输出顺序表
void Print(SqList* L){
for(int i = 0; i < L->length; i++)
printf("%d ",L->data[i]);
}
//按值查找
int LocationElem(SqList *L, ElemType e){
int index = 0;
for(index ; index < L->length; index++)
if(L->data[index] == e)
return index+1;
return 0;
}
//按照位置查找
int GetElem(SqList* L, int index){
if(index < 0 || index > L->length){
printf("输入的范围有错");
return 0;
}
else
retrun L->data[index-1];
}
//插入操作
int ListInsert(SqList *&L, int i, ElemType e){
if(i < 0 || i > L->length + 1){
printf("插入的位置有误!\n");
}
else{
for(int newindex = L->length; newindex >= i; newindex--)
L->data[newindex] = L->data[newindex-1];
L->data[i-1] = e;
L->length += 1;
printf("插入%d元素成功\n",e);
}
return 0;
}
//顺序表的删除
void ListDelete(SqList* &L, int i){
if(i < 0 || i > L->length + 1)
printf("删除的位置有误!\n");
else{
printf("删除前:\n");
PrintList(L);
for(int j = i-1; j < L->length - 1; j++)
L->data[j] = L->data[j+1];
L->length -= 1;
printf("\n");
printf("删除后:\n");
PrintList(L);
}
}
//判空
bool Empty(SqList* L){
bool flag = false;
if(L->length == 0)
flag = true;
return flag;
}
void DestoryList(SqList* L){
free(L);
}
int main(){
SqList* L;
InitList(L);
printf("输入十个元素:\n");
for(int i = 0; i < 10 ; i++)
scanf("%d",&L->data[i]);
PrintList(L);
printf("\n\n");
int len = Length(L);
printf("链表的长度:%d\n\n",len);
printf("输入一个你要查找的值:");
int number = 0;
scanf("%d",&number);
int index = LocationElem(L,number);
printf("该值在线性表的第%d个位置\n\n",index);
printf("输入一个你要查找线性表的位置:");
int Location = 0;
scanf("%d",&Location);
printf("在第%d个位置对应的值:%d\n\n",Location,GetElem(L,Location));
int insertLocation = 0,insertNumber = 0;
printf("在线性表中插入的位置和值:");
scanf("%d %d",&insertLocation,&insertNumber);
ListInsert(L,insertLocation, insertNumber);
PrintList(L);
printf("\n\n");
int deleteLocation = 0;
printf("在线性表中删除的位置");
scanf("%d",&deleteLocation);
ListDelete(L,deleteLocation);
printf("\n\n");
printf("%d",Empty(L));
printf("\n");
DestoryList(L);
}
考研之线性表
最新推荐文章于 2024-06-09 23:18:21 发布