在顺序表中删除所有元素值为x的元素要求空间复杂度为O1。#include iostreamusing namespace std;const int MaxSize=100;typedef int DataType;DataType dataMaxSize;int length;void deleteListDataType elem void show
可以使用双指针法来删除元素。定义两个指针,i指向当前需要判断的元素,j指向当前需要存放的位置。遍历顺序表,如果当前元素不等于x,将其存放到j指向的位置,并将j指针向后移动一位。最后,将j位置之后的所有元素置为0,即完成删除操作。
代码如下:
#include <iostream>
using namespace std;
const int MaxSize = 100;
typedef int DataType;
DataType data[MaxSize];
int length;
void deleteList(DataType elem)
{
int i = 0, j = 0;
while (i < length)
{
if (data[i] != elem)
{
data[j] = data[i];
j++;
}
i++;
}
while (j < length)
{
data[j] = 0;
j++;
}
length = j;
}
void show()
{
for (int i = 0; i < length; ++i)
cout << data[i] << " ";
cout << endl;
}
int main()
{
cin >> length;
for (int i = 0; i < length; ++i)
cin >> data[i];
DataType x;
cin >> x;
deleteList(x);
show();
return 0;
}
时间复杂度为O(n),空间复杂度为O(1)。
原文地址: https://www.cveoy.top/t/topic/i8Ek 著作权归作者所有。请勿转载和采集!