线性表的基础应用
#include<iostream>
using namespace std;
#include<stdlib.h>
typedef struct LNode *PtrToLNode;
#define MAXSIZE 10
struct LNode{
int Data[MAXSIZE];
int Last;
};
typedef PtrToLNode List;
List MakeEmpty(){
List P;
P = (List)malloc(sizeof(struct LNode));
(*P).Last = -1;
return P;
}
bool Insert(List L,int n,int x){
if(L->Last == MAXSIZE - 1)
{
printf("表满");
return false;
}
else if(n<1 || n>L->Last+1+1){
printf("位序不合法");
return false;
}
else{
for(int j = L->Last;j>=n-1;j--)
{
L->Data[j+1] = L->Data[j];
}
L->Data[n-1] = x;
L->Last++;
for(int i = 0 ; i<L->Last+1;i++)
{printf("%d ",L->Data[i]);
}
return true;
return L;}
}
bool Delete(List L,int n){
if(n<1||n>L->Last+1){
printf("删除的位置错误");
return false;
}
else{
for(int i=n-1;i<L->Last;i++){
L->Data[i]=L->Data[i+1];
}
for(int i = 0 ; i<L->Last;i++)
{printf("%d ",L->Data[i]);
}
return true;
}
}
int main(){
List L;
int t,j,n,k,m,p;
L = MakeEmpty();
printf("输入线性表中元素的个数(建议不超过10个):\n");
scanf("%d",&m);
L->Last=m-1;
printf("选择模式:插入或者删除(1代表添加,2代表删除)");
cin>>k;
if(k==2){
printf("输入线性表的元素:\n") ;
for(int i = 0 ; i<L->Last+1;i++)
{cin>>L->Data[i];
printf("选择删除第几号的数字:\n") ;
scanf("%d",&n);
Delete(L,n);}
if(k==1){
printf("输入线性表的元素:\n") ;
for(int i = 0 ; i<L->Last+1;i++)
{cin>>L->Data[i];
}
printf("添加的数字的位置和数字:\n");
scanf("%d%d",&t,&j);
Insert(L,t,j);
}
return 0;}}