动态栈

/*
 * =====================================================================================
 *
 *       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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值