考研之线性表

#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);


}	


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值