在课堂的学习中,我们一般会了解到如何删除线性表中某一个位置pos的值
void SLDelete(SL* ps, int pos) {
assert(ps);
assert(pos >= 0 && pos <= ps->size);
int begin = pos + 1;
while(begin<ps->size)
{
ps->a[begin-1] = ps->a[begin];
}
--ps->size;
}
但是,如果在时间复杂度为O(n),空间复杂度为O(1)的条件下,需要删除线性表之中所有值为item的元素,该如何操作呢?
首先,需要对时间复杂度和空间复杂度进行分析:
时间复杂度为O(n),意味只能遍历线性表1次
空间复杂度为O(1),意味着不能开辟新的空间,通过空间换时间,需要进行原地运算
下面,我们进行算法的分析,假设线性表中依次存储5 4 4 7 4 这五个元素,item为4,
方法一:(遍历时移动)
如下图:
绿色表示需要保留的元素
void SLErase(SL* ps, SLDataType item) {
assert(ps);
int flag = 0;//记录值不为x的元素的个数
//第一步:
for (int i = 0; i < ps->size; i++) {
if (ps->a[i] != item) {
ps->a[flag] = ps->a[i];
flag++;
}
}
//第二步:
ps->size = flag;
}
方法二:(双指针)
若指针1指向的元素为 item,指针1向后移动
若指针1指向的元素不为 item,将指针1指向的值赋给指针2指向的值,然后指针1和指针2均向后移动
最后,将指针2表示的值(目标元素的个数)赋给ps->size.
void SLErase(SL* ps, SLDataType item) {
assert(ps);
int src = 0, dst = 0;//两个指针
while (src < ps->size) {
if (ps->a[src] != item) {
ps->a[dst++] = ps->a[src++];
}
else
src++;
}
ps->size = dst;
}
下面,我们对以上两个函数进行验证:
方法一验证
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#define INT_CAPACITY 10
//动态顺序表
typedef int SLDataType;
typedef struct SqList {
SLDataType* a;
int size;//存储数据个数
int capacity;//存储空间大小
}SL;
//初始化
void InitList(SL* ps) {
assert(ps);
ps->a = (SLDataType*)malloc(sizeof(SLDataType) * INT_CAPACITY);
if (ps->a == NULL) {
perror("malloc fail");
return;
}
ps->size = 0;
ps->capacity = INT_CAPACITY;
}
void SLErase(SL* ps, SLDataType item) {
assert(ps);
int flag = 0;//记录值不为x的元素的个数
for (int i = 0; i < ps->size; i++) {
if (ps->a[i] != item) {
ps->a[flag] = ps->a[i];
flag++;
}
}
ps->size = flag;
}
//打印线性表元素
void SLPrint(SL* ps) {
assert(ps);
for (int i = 0; i < ps->size; i++) {
printf("%d ", ps->a[i]);
}
printf("\n");
}
//在线性表中插入元素
void SLInsert(SL* ps, int pos, SLDataType x) {
assert(ps >= 0 && pos <= ps->size);
int end = ps->size - 1;
while (end >= pos) {
ps->a[end + 1] = ps->a[end];
--end;
}
ps->a[pos] = x;
ps->size++;
}
int main() {
SL s;
InitList(&s);
SLInsert(&s, 0, 5);
SLInsert(&s, 1, 4);
SLInsert(&s, 2, 4);
SLInsert(&s, 3, 7);
SLInsert(&s, 4, 4);
//SLErase(&s, 4);
//此处注释,呈现原链表元素情况
SLPrint(&s);
}
运行SLErase函数后
方法二验证结果相同。