栈和队列,作为计算机中很重要的两种数据结构,它们的数据组织方式均可用数组和链表实现,只是存取数据时的方式有所差别。一个是遵循“先进后出”,一个是遵循“先进先出”的原则。
链表实现:
#include<stdio.h>
#include<stdlib.h>
struct Node;
typedef struct Node *ptrtonode;
typedef ptrtonode stack;
typedef int element_type;
struct Node{
element_type x;
ptrtonode next;
};
int is_empty(stack s);
stack initial(void);
void make_empty(stack s);
void push(stack s,element_type x);
element_type pop(stack s);
element_type top(stack s);
void main(){
stack sk;
element_type a;
sk = initial();
push(sk, 2);
push(sk, 4);
push(sk, 8);
printf("stcak is null\n?", is_empty);
for (int i = 0; i < 3; i++){
a = pop(sk);
printf("pop:%d\n", a);
}
printf("stack is null?\n", is_empty);
}
int is_empty(stack s){
return s->next == NULL;
}
stack initial(stack s){
s = (ptrtonode)malloc(sizeof(struct Node));
if (s = NULL)
printf("out of space!\n");
s->next = NULL;
return s;
}
void make_empty(stack s){
if (s = NULL)
printf("erro");
else
while (s->next != NULL)
pop(s);
}
element_type pop(stack s){
ptrtonode top;
element_type element;
if (is_empty(s))
printf("erro");
else{
top = s->next;
element = top->x;
s ->next = s->next->next;
//return element;
}
return element;
free(top);
}
void push(stack s, element_type x){
ptrtonode a;
a = (ptrtonode)malloc(sizeof(struct Node));
if (a = NULL)
printf("erro");
else{
a->x = x;
a->next = s->next;
s->next = a;
}
}
element_type top(stack s){
element_type top;
if (s = NULL)
printf("erro");
else{
top = s->next->x;
}
return top;
}