栈的创建入栈出栈
#include<stdio.h>
#include<stdlib.h>
typedef struct node //结点结构
{
int data;
struct node *next;
}Node, *Pnode;
typedef struct stack //栈结构
{
Pnode top;
Pnode bottom;
}Stack, *Pstack;
void init(Pstack); //栈的初始化
void push(Pstack, int number); //入栈
void pop(Pstack); //出栈
void Traversal(Pstack); //遍历栈
int main(void)
{
Pstack p;
init(&p); //栈的初始化
push(&p, 1); //入栈
push(&p, 2); //入栈
push(&p, 3); //入栈
push(&p, 4); //入栈
push(&p, 5); //入栈
Traversal(&p); //遍历栈
pop(&p); //出栈
Traversal(&p); //遍历栈
return 0;
}
void init(Pstack p) //栈的初始化
{
p->top = (Stack *)malloc(sizeof(Stack));
if(p->top == NULL)
{
printf("栈初始化失败!\n");
exit(-1);
}
else
{
p->top = p->bottom;
p->top->next = NULL;
}
return;
}
void push(Pstack p, int number) //入栈
{
Node *w;
w = (Node *)malloc(sizeof(Node));
w->data = number;
w->next = p->top;
p->top = w;
return;
}
void pop(Pstack p) //出栈
{
Node *w;
if(p->top == p->bottom)
{
printf("此栈为空!\n");
exit(-1);
}
else
{
w = p->top;
p->top = p->top->next;
free(w);
}
return;
}
void Traversal(Pstack p) //遍历栈
{
Node *w;
w = p->top;
while(w != p->bottom)
{
printf("%d ",w->data);
w = w->next;
}
printf("\n");
return;
}