栈在C中怎么实现?

发布网友 发布时间:2022-04-20 09:58

我来回答

2个回答

热心网友 时间:2023-07-10 04:42

#include<stdio.h>
#include<malloc.h>
//enum bool {false,true};

typedef struct Node{
int a;
int Number; //在栈中的序号,栈底为0
struct Node *next;
}Node,*LpNode;

typedef struct SqStack{
Node *top;
Node *prev;
Node *base;
int length;
}*LpSqStack;

//将e的能容复制到S中并将e摧毁
bool Node_evaluation(LpNode S,LpNode e,bool M)
{
//赋值操作
//S->Number = e->Number;
if(M == true) free(e);
return true;
}
bool InitStack(LpSqStack S)
{
S->length = 0;
S->base = (LpNode)malloc(sizeof(Node));
if(!S->base) return false;
S->top = S->base;
S->prev = S->base;
S->base->Number = 0;
return true;
}

bool StackEmpty(LpSqStack S)
{
if(S->top != S->base) return false;
return true;
}

bool GetTop(LpSqStack S,LpNode e)
{
if(S->top == S->base) return false;
e = S->top;
return true;
}

bool Push(LpSqStack S,LpNode e)
{
if(!Node_evaluation(S->top,e,true)) return false;
S->top->Number = S->prev->Number + 1;
S->prev = S->top;
S->top = (LpNode)malloc(sizeof(Node));
S->prev->next = S->top;
S->top->next = NULL;
return true;
}

bool Pop(LpSqStack S,LpNode e)
{
if(S->top == S->base) return false;
if(!Node_evaluation(e,S->top,true)) return false;
S->top = S->prev;
S->top->next = NULL;
return true;
}

bool Vistit(LpSqStack S,LpNode e,int i)
{
LpNode p;
p = S->base;
for(int j = 0; j = i; j++)
{
if(p->next == NULL) return false;
p = p->next;
}
if(!Node_evaluation(p,e,false)) return false;
return true;
}

int main()
{
SqStack a;
InitStack(&a);
LpNode b=new Node;
LpNode c=new Node;
LpNode d=new Node;
//free(&b);这free了你下面又赋值。。。
b->a=1;
Push(&a,c);
GetTop(&a,c);
printf("%d",c->a);
return 0;
}
栈里的内存是不能free的,你要free你就自己在堆里分配。

热心网友 时间:2023-07-10 04:43

你写的太复杂,这个拿去用吧
// Stack node
struct Node
{
int data ;
Node* next ;
Node(int d, Node* p):data(d), next(p){}
};

class Stack
{
public:
Stack():top(NULL){}

void Push(int d)
{
top = new Node(d, top) ;
}

int Pop()
{
Node* temp = top ;
top = top->next ;
return temp->data ;
}

bool Empty()
{
return top == NULL ;
}

private:
Node* top ;
};

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com