急急急!!栈链插入与删除运算
如何补充?
#include<iostream>
#define NULL 0
using namespace std;
typedef int datatype;
typedef struct node
{
datatype node *next;
struct node *next;
}linkstack;
linkstack *top;
linkstack push_lstack(linkstack *top,datatype x) //进栈
{
linkstack *p;
p=(node*)malloc(sizeof(linkstack));
p->data=x;
p->next =top;
top=p;
return(top);
}
linkstack pop_lstack(linkstack *top,datatype *datap) //出栈
{
linkstack *p;
if(top==null)
{
cout<<"空栈!";
return (NULL);
}
else
{
*datap=top->data;
p=top;
top=top->next;
free(p);
return(top);
}
}
int main()
{
}
[解决办法]
#include "stdafx.h"
Status InitStack(stack* s)
{
//构造一个空栈
s->base = (SElemType*) malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(s->base==NULL) return ERROR;
s->top = s->base ; //表示空栈
s->stacksize = STACK_INIT_SIZE ;
return OK;
}
Status DestroyStack(stack* s)
{
//销毁栈s,s不再存在
free(s->base);
s->top =s->base =NULL;
free(s);
return 0;
}
Status ClearStack(stack* s)
{
//把栈s清空
s->top = s->base ;
return OK;
}
int StackEmpty(stack* s)
{
//若栈s为空,则返回true, 否则返回false
if(s->top == s->base) return 1;
return 0;
}
int StackLength(stack* s)
{
//返回s的元素的个数,即栈的长度
return s->top - s->base;
}
Status GetTop(stack* s,SElemType* e)
{
// 若栈不空,则用e返回s的栈顶元素,操作成功返回0 ,失败返回-1
if(s->top==s->base) return ERROR;
*e= *(s->top-1);
return OK;
}
Status Push(stack* s,SElemType e)
{//插入元素e为新栈顶的元素
if(s->top-s->base >= s->stacksize)
{ //栈滿,追加存储空间
s->base = (SElemType* ) realloc(s->base,(s->stacksize+STACKINCRAMENT)*sizeof(SElemType));
if(s->base==NULL) return ERROR;
s->top = s->base +s->stacksize;
s->stacksize += STACKINCRAMENT;
}
*(s->top)++ = e;
return OK;
}
Status Pop(stack* s,SElemType* e)
{ //若栈不空,则删除s的栈顶元素,用e返回其值
//操作成功返回0 ,失败返回-1
if(s->top==s->base) return ERROR;
*e = *(--s->top);
return OK;
}
Status StackTraverse(stack* s)
{
//从栈顶依次对栈中的每一个元素进行遍历
SElemType* temp = s->top;
for(temp--;temp!=s->base-1;temp--)
{
printf("%d ",*temp);
}
printf("\n");
return OK;
}