#include <stdio.h>
#include <stdlib.h>
#define NULL 0
typedef struct Stack *S1;
typedef struct Node
{
int Element;
Node *next;
}Snode,*node;
struct Stack
{
Snode *top;
};
S1 InitStack()
{
S1 s;
s=(S1)malloc(sizeof(struct Stack));
s->top=(node)malloc(sizeof(struct Node));
s->top->next=NULL;
s->top->Element=NULL;
return s;
}
void Push(int x,S1 s)
{
node n;
n=(node)malloc(sizeof(struct Node));
if(!n)
exit(-1);
n->Element=x;
n->next=s->top->next;
s->top->next=n;
}
int Pop(S1 s)
{
if(s->top->next!=NULL)
{
int i;
node p=s->top->next;
i=p->Element;
s->top->next=p->next;
free(p);
return i;
}
else
exit(-1);
}
void main()
{
S1 st;
int i;
st=InitStack();
Push(1,st);
Push(2,st);
Push(3,st);
i=Pop(st);
printf("%d\n",i);
Push(5,st);
Push(9,st);
i=Pop(st);
printf("%d\n",i);
}
用一个单链表L实现一个栈 要求PUSH和POP操作的时间仍为O(1) 算法导论10.2-2答案
最新推荐文章于 2023-11-01 23:22:51 发布