1230: 删除顺序表中指定值的所有元素
题目描述
利用顺序表表示一个包括n个整数的序列,请实现一个时间复杂度为O(n),空间复杂度为O(1)的算法,该算法可以删除表中所有值为item的元素。
输入
多组数据,每组数据有三行,第一行为顺序表的长度n,第二行为顺序表的n个元素(元素之间用空格分隔),第三行为待删除的元素的值item。当n=0时输入结束。
输出
对于每组数据分别输出一行,依次输出删除值为item的元素后顺序表中的剩余元素,元素之间用空格分隔。
样例输入
5
44 11 22 33 22
11
6
22 33 11 33 33 55
33
0
样例输出
44 22 33 22
22 11 55
提示
数据保证删除之后链表中至少存在一个元素
C++
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
typedef int Status;
typedef struct
{
int *elem;
int length;
}SqList;
Status InitList(SqList &L)
{
L.elem=new int[MAXSIZE];
if(!L.elem) exit(OVERFLOW);
L.length=0;
return OK;
}
void CreateList(SqList &L,int n)
{
L.length=n;
for(int i=0;i<n;i++)
cin >> L.elem[i];
}
void DeleteList(SqList &L,int k)
{
for(int i=0;i<L.length;i++)
{
if(L.elem[i]==k)
{
for(int j=i;j<L.length-1;j++)
{
L.elem[j]=L.elem[j+1];
}
L.length--;
i--;
}
}
}
void DispList(SqList L)
{
for(int i=0;i<L.length;i++)
cout << L.elem[i] << ' ';
cout << endl;
}
int main()
{
int n;
while(cin >> n,n!=0)
{
SqList L;
InitList(L);
CreateList(L,n);
int k; cin >> k;
DeleteList(L,k);
DispList(L);
}
return 0;
}