这里分享一下简单的静态栈的操作。代码简单,就不作注释和解释了
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 5
struct Node
{
int *base;
int *top;
int size;
} node;
void print()
{
int *p;
p = node.top;
while(p-node.base > 0) //top刚开始是N,所以要大于0
{
p--;
printf("%d ",*p);
}
putchar('\n');
}
void init()
{
node.size = N;
node.base = (int*)malloc(sizeof(int));
node.top = node.base;
printf("node.base = %d, node.top = %d\n",node.base,node.top);
puts("Init!----");
int i=0;
while(node.top < node.base+node.size)
{
*node.top = i++;
node.top++;
}
puts("After Init----");
print();
}
void mypush(int temp)
{
if(node.top-node.base >= node.size)
printf("\nPush failed, the stack is full!\n");
else
{
printf("\nPush success, the push number is %d\n",temp);
*node.top = temp;
node.top++;
puts("\nAfter push----");
print();
}
}
int* mypop()
{
if(node.top == node.base)
{
puts("\nPop failed, the stack is empty!");
return NULL;
}
else
{
node.top--;
printf("The pop number is %d\n",*node.top);
puts("\nAfter pop----");
print();
return node.top;
}
}
int main()
{
int* p;
init();
mypush(100);
p = mypop();
if(p != NULL)
printf("p = %d\n",*p);
mypush(100);
return 0;
}