删除线性表中所有值为item的数据元素

/*(6)已知长度为n的顺序存储结构表A,写一个时间复杂度为o(n)
空间复杂度为o(1)的算法,删除线性表中所有值为item的数据元素*/
//after all, what's the border of difficulty
#include<stdio.h>
#include<iostream.h>
#include<malloc.h>
#include<cstdlib>//包含exit头文件
#include<math.h>
#include<string>
#define MAXSIZE 100
#define OK 1
#define ERROR 0//宏
typedef int Status;
using namespace std;
typedef struct
{
    char name[20];
}
Elemtype;//其实我真的搞不懂了string真的好麻烦
typedef struct
{
    Elemtype *data;//基地址
    int length;//表长n
}SqList;
Status InitList(SqList &L)
{
    L.data=(Elemtype *)malloc(MAXSIZE*sizeof(Elemtype));
    //返回给data一个基地址
    if(!L.data) exit(OVERFLOW);
    L.length=0;
    return OK;
}
Status EnterData_Sq(SqList &L)
{//data enter for test
    int length;    Elemtype e;
    cout<<"もう言いたくない、もう…"<<endl;
    cin>>length;
    cout<<"データ、くれないかなあ?"<<endl;
    for(int i=0;i<length;i++)
    {
        cin>>e.name;
        L.data[i]=e;
        L.length++;
    }
    return OK;
}
Status LocateElem(SqList L,Elemtype e)
{//找到第一个item
    for(int i=0;i<L.length;i++)//时间复杂度o(n)
    {
        if(!strcmp(L.data[i].name,e.name)) return i+1;//返回位置序号
    }
    return ERROR;
}
Status DeleteElem(SqList &L,Elemtype e)
{
    int i=LocateElem(L,e);
    int step=1;//移动步数
    if((i<1)||(i>L.length)) return ERROR;//illegal i
    for(int j=i;j<L.length;j++)//时间复杂度为o(n),时间耗费在元素移动上最多移动n-1个
    {
        if(!strcmp(L.data[j].name,e.name))
        {
            step++;
        }else
        {//其余保留
            L.data[j-step]=L.data[j];       
        }
    }
    L.length=L.length-step;
   
    return OK;
}
void ShowList(SqList L)
{
    for(int i=0;i<L.length;i++)
    {
        cout<<L.data[i].name<<endl;
    }
}
void main()
{
    SqList L;
    Elemtype e;
    strcpy(e.name,"1");//简单起见,data为char "1"
    InitList(L);
    EnterData_Sq(L);
    cout<<"all ends all starts:"<<endl;
    ShowList(L);
    DeleteElem(L,e);
    cout<<"what's going on?"<<endl;
    ShowList(L);
    system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值