#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Node{
int value;
struct Node * next;
}NODE,*PNODE;
typedef struct Stack{
PNODE top;
PNODE bottom;
}STACK,*PSTACK;
void init_stack(PSTACK pStack);
void push(PSTACK pStack);
void pop(PSTACK pStack);
void traverse_stack(PSTACK pStack);
bool is_empty(PSTACK pStack);
void gettop(PSTACK pStack,int *top);
void getlen_stack(PSTACK pStack,int *len);
void clean_stack(PSTACK pStack);
void destroy_stack(PSTACK pStack);
int main(void)
{
freopen("in.txt","r",stdin);
STACK stack;
init_stack(&stack);
push(&stack);
traverse_stack(&stack);
int top,len;
gettop(&stack,&top);
getlen_stack(&stack,&len);
printf("THE TOP OF THE STACK IS %d
",top);
printf("THE LEN OF THE STACK IS %d
",len);
pop(&stack);
gettop(&stack,&top);
getlen_stack(&stack,&len);
printf("THE TOP OF THE STACK IS %d
",top);
printf("THE LEN OF THE STACK IS %d
",len);
clean_stack(&stack);
traverse_stack(&stack);
destroy_stack(&stack);
traverse_stack(&stack);
return 0;
fclose(stdin);
}
void init_stack(PSTACK pStack)
{
pStack->top = pStack->bottom = NULL;
}
void push(PSTACK pStack)
{
int val;
while(scanf("%d",&val) && val!= -1){
PNODE p = (PNODE)malloc(sizeof(Node));
p->next = NULL;
p->value = val;
if(pStack->bottom==NULL&&pStack->top==NULL){
pStack->top = pStack->bottom = p;
}else{
p->next = pStack->top;
pStack->top = p;
}
}
}
void traverse_stack(PSTACK pStack)
{
PNODE p = pStack->top;
if(false == is_empty(pStack)){
while(p){
printf("%d ",p->value);
p = p->next;
}
printf("
");
}else{
printf("SORRY The stack is empty!
");
}
}
bool is_empty(PSTACK pStack)
{
if(pStack->top == NULL && pStack->bottom == NULL){
return true;
}else{
return false;
}
}
void gettop(PSTACK pStack,int *top)
{
if(false == is_empty(pStack)){
*top = pStack->top->value;
}else{
printf("SORRY The stack is empty!
");
}
}
void pop(PSTACK pStack)
{
PNODE p = pStack->top;
pStack->top = p->next;
free(p);
}
void getlen_stack(PSTACK pStack,int *len)
{
PNODE p = pStack->top;
int cnt = 0;
if(false == is_empty(pStack)){
while(p){
cnt++;
p = p->next;
}
*len = cnt;
}else{
printf("SORRY The stack is enpty!
");
}
}
void clean_stack(PSTACK pStack)
{
PNODE p = pStack->top;
if(false == is_empty(pStack)){
while(p){
p->value = 0;
p= p->next;
}
}else{
printf("SORRY The stack is enpty!
");
}
}
void destroy_stack(PSTACK pStack)
{
PNODE p = pStack->top;
PNODE q = NULL;
if(false == is_empty(pStack)){
while(p){
p = p->next;
pop(pStack);
}
printf("%d",pStack->bottom->value);
}else{
printf("SORRY The stack is enpty!
");
}
}