顺序线性表的删除算法 C语言版

顺序线性表的删除算法:

算法部分:

Status ListDelete_Sq ( SqList &L, int i, ElemType &e ) {

// 在顺序线性表L中删除第 i 个元素,并用 e 返回其值,1≤i ≤ListLength_Sq (L)

if ( ( i < 1 ) || ( i > L.length ) ) return ERROR; // i 值不合法

p = &( L.elem [ i-1 ] ); // p 为被删除元素的位置

e = *p; // 被删除元素的值赋给 e

q = L.elem + L.length – 1; // 表尾元素的位置

for ( ++p; p <= q; ++p ) *(p-1) = *p; // 被删除元素之后的元素左移

--L.length; // 表长减 1

return OK;

} // ListDelete_Sq



C程序源代码部分:


//ListDelete_Sq.cpp
//Delete the NO.i Element of Sq_List and get the value

#include <stdlib.h>
#include <iostream.h>
#include <conio.h>
#include <stdio.h>

//#define LIST_INIT_LENGTH 10 //LIST_INIT_LENGTH is the Init_Define_Length of Sq_List
//int array[LIST_INIT_LENGTH]={5,8,12,18,25,30,37,46,51,89};
//array use to assign init value of SqList
#define ElemType int
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef struct
{ int *elem;
int length;
int listsize;
}SqList;

int InitList_Sq(SqList &L) //InitList_Sq() function
{ //Inititial a Sq_List
L.elem=(int *)malloc(LIST_INIT_SIZE *sizeof(int));
if (!L.elem) return(0);
L.length=0;
L.listsize=LIST_INIT_SIZE;
return(1);
}//end of InitList_Sq() function

void ListDelete_Sq(SqList &L,int i, int &e) //ListDelete_Sq() function
{
int *p,*q;
if((i<1)||(i>L.length))
{ cout<<i<<" is OverFlow !"<<endl;
exit(0);
}
p=&(L.elem[i-1]);
e=*p;
q=L.elem+L.length-1;
for (++p;p<=q;++p)
*(p-1)=*p;
--L.length;
cout<<"Success to Delete Sq_list !"<<endl;
}//end of ListDelete_Sq() function

void main() //main() function
{
SqList L;
int e;
int i,j;
//L.elem=array;
//L.length=LIST_INIT_LENGTH;
cout<<"ListDelete_Sq.cpp"<<endl<<"================="<<endl<<endl;

InitList_Sq(L);
cout<<"Please input the Length of Demo SqList L: <eg. 5> ";
cin>>L.length;
cout<<"Please input the data of Demo SqList L: <eg. {34,54,30,2,40,...}> "<<endl;
for(j=0;j<L.length;j++)
cin>>L.elem[j];

cout<<endl;
cout<<"Success to create a SqList:"<<endl;
cout<<"Please input the NO.i element of Sq_List to delete: <eg. 3> ";
cin>>i;
ListDelete_Sq(L,i,e);
cout<<"The SqList After Delete is: ";
for(j=0;j<L.length;j++)
cout<<L.elem[j]<<" ";
cout<<endl<<"...OK...!"<<endl;
getch();
}//end of main() function


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值