数据结构(算法)-线性表(顺序表)




/**
1,空的线性表setNull(L)
2,insert 加入元素
3,根据位置查找元素
4,查找所有元素
5,删除一个元素	
*/

#include <iostream>

using namespace std;

#define MaxSize 50

typedef char ElemType;

struct List{
	ElemType list[MaxSize];
	int size;
};

void setNull(struct List *p){
	p->size=0;
}


void insert(struct List *p , ElemType x , int i){
	int j;
	if(i<1 && i>p->size+1){
		cout<<"超出线性表"<<endl;
	}else{
		p->size++;						//长度加1
		for(j=p->size-1 ; j>= i; j--){  //如果在前面加入
			p->list[j]=p->list[j-1];	//后移增加一个空间
		}
		p->list[j] = x;					//数据加入增加的空间
	}
}

void display(struct List *p ){
	int j;
	if(p->size==0){
		cout<<"顺序表为空"<<endl;
	}else{
		cout<<"顺序表"<<endl;
		if(p->size ==1){
			cout<<p->list[p->size]<<endl;
		}else{
			for(j=0; j<p->size-1; j++){
				printf("%c ->",p->list[j]);
			}
			printf("%c",p->list[j]);
		}
		printf("\n");

	}
}

void del(struct List *p , int i){
	int j;
	if(i>p->size || i<1){
		cout<<"超出线性表"<<endl;
	}else{
		
		for(j=i-1; j<p->size-1;j++){ //向前移一位
			p->list[j]=p->list[j+1]; //后面覆盖前面
		}
		p->size--;//长度减一
	}
		
}

void main(){
	struct List L;
	setNull(&L);
	insert(&L,'a',1);
	insert(&L,'b',2);
	insert(&L,'a',1);
	insert(&L,'c',2);

	display(&L);
	del(&L,2);
	display(&L);
	del(&L,2);
	display(&L);

}




 

测试结果

顺序表
a ->c ->a ->b
顺序表
a ->a ->b
顺序表
a ->b

 

转载于:https://my.oschina.net/saulc/blog/2243889

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值