数据结构习题练习——删除线性表中值为item的元素

文章讨论了在限制时间复杂度为O(n)和空间复杂度为O(1)的情况下,如何从线性表中删除所有值为item的元素。提供了两种方法:遍历移动和双指针法,分别详细阐述了这两种方法的实现过程,并通过代码示例进行了验证。
摘要由CSDN通过智能技术生成

        在课堂的学习中,我们一般会了解到如何删除线性表中某一个位置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函数后

 方法二验证结果相同。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值