怎样用C语言写出对栈进行的五种运算:push()、pop()、top()、empty()、makempty()

2024-12-05 05:47:33
推荐回答(2个)
回答1:

这是我用链表写的:
#include
#include

typedef struct node
{
int x;
struct node *next;
}Node;

typedef struct stack
{
Node *top;
}Stack;

void InitStack(Stack *s)
{
s->top=NULL;
}

int IsEmpty(Stack *s)
{
if(s->top==NULL)
return 1;
else
return 0;
}
void PushStack(Stack *s,int x)
{
Node *p;
p=(Node*)malloc(sizeof(Node));
p->x=x;
// p->next=NULL;

p->next=s->top;
s->top=p;
}

int PopStack(Stack *s)
{
int data;
Node *p;
p=(Node *)malloc(sizeof(Node));
if(IsEmpty(s))
{
printf("the stack is empty!\n");
free(p);
return -1;
}
else
{
p=s->top;
data=p->x;
s->top=p->next;
free(p);
return data;
}
}

int main (int argc,char **argv)
{
int i;
Stack s;
InitStack(&s);
for(i=0;i<1000;i++)
{
PushStack(&s,i);
}
for(i=0;i<1000;i++)
{
printf("%d\n",PopStack(&s));
}
}

回答2:

我写伪代码,你自己添加就可以了顺序栈你可以这样定义#define MAX_STACK_SIZEint stack[MAX_STACK_SIZE]int pointer=0;push(int x){ if(pointer

pointer++;} else printf("栈满");}int pop(){ if(pointer>0) { pointer--; return stack[pointer]; } else printf("栈空");}int top(){ return stack[pointer-1];}bool empty(){ return pointer==0} makempty(){ memset(stack,0,MAX_STACK_SIZE); pointer=0;}