动态栈

来源:互联网 发布:土地确权数据库建设 编辑:程序博客网 时间:2024/04/30 10:56
/*
 * =====================================================================================
 *
 *       Filename:  dynamic_stack.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2011年10月25日 16时53分20秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Wang Ran (), wangran51@126.com
 *        Company:  
 *
 * =====================================================================================
 */
#include <stdio.h>
#include <stdlib.h>
struct stack_node
{
int data;
struct stack_node *next_ptr;
};


void push(struct stack_node** node, int n);
int pop(struct stack_node** node);
int is_empty(struct stack_node* node);
void print_stack(struct stack_node* node);
void  instructions(void);


int main()
{
struct stack_node * stack_ptr = NULL;//在第第一次push的时候NULL会被复制到top_ptr->next_ptr中
    //所以这句是必须的
int i, choice, value;


for(i=0; i<5; i++)
{
printf("Enter an interger:");
scanf("%d", &value);
push(&stack_ptr, value);
// print_stack(stack_ptr);
}


for(i=0;i<5;i++)
{


if(!is_empty(stack_ptr))
{
printf("the poped value is %d\n ", pop(&stack_ptr));
}
print_stack(stack_ptr);
}

printf("end of run \n ");




return EXIT_SUCCESS;
}


void instructions(void)
{
printf("Enter choice: \n 1:push\n 2:pop\n 3:end\n ");
}
void push(struct stack_node ** top_ptr, int info)
{
struct stack_node * new_ptr;
new_ptr = malloc(sizeof (struct stack_node));
if(new_ptr != NULL)
{
new_ptr->data = info;
new_ptr->next_ptr = *top_ptr;
*top_ptr = new_ptr;
}
else
{
printf("%d not inserted, No memory available. \n", info);
}
}
int pop(struct stack_node** top_ptr)
{
struct stack_node* temp_ptr;
int pop_value;
temp_ptr = *top_ptr;
pop_value = (*top_ptr)->data;
*top_ptr = (*top_ptr)->next_ptr;
free(temp_ptr);
return pop_value;
}
void print_stack(struct stack_node* current_ptr)
{
if(current_ptr == NULL)
{
printf("the stack is empty.\n");
}
else
{
while(current_ptr != NULL)
{
printf("%d-->", current_ptr->data);
current_ptr = current_ptr->next_ptr;
}
printf("NULL\n ");
}
}
int is_empty(struct stack_node * top_ptr)
{
return top_ptr == NULL;
}
原创粉丝点击