您的位置:首页 > 其它

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

2013-05-22 21:58 681 查看
#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 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐