注册 登录
编程论坛 C++教室

如何删除元素?

henji 发布于 2009-11-04 20:34, 708 次点击
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define ERROR -1
#define OVERFLOW -2
typedef  int SElemType;
typedef  int Status;

typedef struct
{
    SElemType *base;
    SElemType *top;
    int stacksize;
}SqStack;

Status InitStack(SqStack &S)
{
    int n=0;
    int a=0;
    S.base=(SElemType *)malloc(STACK_INIT_SIZE *sizeof(SElemType));
    if(!S.base)exit(OVERFLOW);
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
    if(!S.base)
    {
        printf("malloc error!\n");
        exit(0);
    }
    printf("please input a number:\n");
    scanf("%d",&n);
    printf("the number is %d\n",n);
    while(n>0)
    {
        scanf("%d",&a);
        *S.top++=a;
        n--;
    }
    return OK;
}

void print(SqStack S)
{
    while(S.base!=S.top)
    {
        printf("%4d",*--S.top);
    }
    printf("\n");
}

Status Push(SqStack &S)
{
    int e;
    if(S.top-S.base>=S.stacksize)
    {
        S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
        if(S.base)exit(OVERFLOW);
        S.top=S.base+S.stacksize;
        S.stacksize+=STACKINCREMENT;
    }
    printf("input the insert number:\n");
    scanf("%d",&e);
    *S.top++=e;
    return OK;
}

Status Pop(SqStack &S)//这个函数如何实现删除功能?代码该如何编写?
{
    int e;
    if(S.top==S.base)
    {
        return ERROR;
    }
    printf("input the delete number\n");
    scanf("%d",&e);
    e=*--S.top;
    if(*S.top==e)
    {
        S.top--;
    }
    return OK;
}

Status GetTop(SqStack S)
{
    int c;
    if(S.top==S.base)
    {
        printf("error!\n");
    }
    c=*(S.top-1);
    printf("zhanding is %d\n",c);
    return OK;
}

int main(int argc, char* argv[])
{
    SqStack S;
    int c=0;
    InitStack(S);
    print(S);
    Push(S);
    print(S);
    Pop(S);
    print(S);
    GetTop(S);
    return 0;
}

6 回复
#2
qlc002009-11-04 22:07
如果你要想删除所有的数的话可以让top=base=NULL;单个元素的删除就是一次出栈。
#3
henji2009-11-04 23:58
要如何加代码啊?
#4
qlc002009-11-05 00:09
比如定义一个函数如
void clearlist(SqStack S)
{
    s.base=s.top=NULL;
}
#5
henji2009-11-05 00:17
是输入一个数和所有的元素比较,如果有相同的就删除,不是删除所有的数?
#6
flyingcloude2009-11-05 12:29
回复 5楼 henji
这样有些麻烦,先找到相同数在堆栈中 的位置,然后让在这个数之上的数出栈,再让找到的这个数出栈,最后让其他数重新进栈
#7
西曦2013-07-21 13:44
有没有不用链表做的方法啊
1