顺序表的相关操作+删除+添加+遍历+逆序

#include<iostream>
using namespace std ;
#define MAXSIZE 100 //初始分配的大小
#define ADDSIZE 10 //内存不够每次增加的内存
typedef struct List
{
	char *Elem ;
	int Length ;
	int ListSize ;
}List ;

/*创建链表*/
void CreateList(List &L)
{
	L.Elem = (char *)malloc(MAXSIZE * sizeof(char)) ;
	if(!L.Elem)
	{
		cout<<"overflow"<<endl ;
		exit(1) ;
	}
	L.Length = 0 ;
	L.ListSize = MAXSIZE ;
}

/*插入数据到链表*/
void InsertList(List &L, int pos , char e)
{
	if(pos < 0 || pos > L.Length + 1 ) //插入的位置不争正确
	{
		cout<<"pos is wrong "<<endl ;
		return ;
	}
	if(L.Length >= L.ListSize )  //空间不够,增加空间
	{
		char * newbase ;
		newbase = (char *) realloc(L.Elem , (L.ListSize + ADDSIZE) * sizeof(char));
		if(!newbase)
		{
			cout<<"overflow"<<endl ;
			exit(1) ;
		}
		L.Elem = newbase ;
		L.ListSize += ADDSIZE ;
	}
	char * p;
	p= &L.Elem[pos-1] ; //指向要插入位置的指针
	char *q ;
	q= &L.Elem[L.Length - 1] ; //指向最后一个元素的指针
	while(q >= p)
	{
		*(q+1) = *q ;
		q-- ;
	}
	*p = e ;
	L.Length ++ ;
}

/*遍历链表*/
void TraList(List L)
{
	int i = 0 ;
	while( i < L.Length )
		cout<<L.Elem[i++] ;
	cout<<endl ;
}

/*删除数据*/
char DeleteList(List &L , int pos)
{
	if(pos < 0 || pos > L.Length + 1 )
	{
		cout<<"pos wrong"<<endl;
		return -1;
	}
	char * p ;
	p = &L.Elem[pos - 1] ;
	char e = *p ;
	int i = pos  ;
	while( i <L.Length){
		*p = *(p+1) ;
		p++ ;
		i ++;
	}
	L.Length -- ;
	return e ;
}

/*将链表逆序*/
void Reserve(List &L)
{
	int i = 0 , j = L.Length -1 ;
	while( i<= L.Length/2 - 1)
	{
		char tmp ;
		tmp = L.Elem [i] ;
		L.Elem [i] = L.Elem[j] ;
		L.Elem[j] = tmp ;
		i ++ ;
		j -- ;
	}
}
int main(void)
{
	List L;
	CreateList(L) ;
	char e ;
	int i ;
	cout<<"输入你要插入的数据:(当输入数据'q'时结束)"<<endl;
	//while(cin >> e && e!='q'){
	//	cin >> i ;
	for( int j = 1 ; j <=10 ; j ++){
		e = j+'A'-1 ;
		i = 1; 
		InsertList(L , i , e) ;
	}
//	}
	TraList(L);	
	
	cout << "将链表逆序"<<endl ;
	Reserve(L);
	TraList(L);

	cout<<"输入你要删除的数据的位置:(输入0结束)"<<endl;
	while(cin >> i && i){
		e = DeleteList(L,i) ;
		cout<<"删除的数据是:"<< e <<endl ;
		TraList(L ) ;
	}
	
	return 0 ;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值