用链表实现栈

来源:互联网 发布:程序员 1000万 编辑:程序博客网 时间:2024/06/03 18:53
#include <stdio.h>
#include <stdlib.h>
/*定义结构体,用户自定义*/
struct node
{
int num;
struct node * next;
};


typedef struct node Node;
typedef struct node * Link;
enum return_result{EMPTY_OK,EMPTY_NO,PUSH_OK,PUSH_NO,POP_OK,POP_NO};
/*分配单元*/
void is_malloc_ok(Link new_node)
{
     if(new_node == NULL)
{
printf("malloc error!\n");
exit(-1);
}
}


void create_newnode(Link * top)
{
*top = (Link) malloc(sizeof(Node));
is_malloc_ok(*top);
}


void create_stack(Link *top)
{
*top = (Link) malloc(sizeof(Node));
is_malloc_ok(*top);
}
/*初始化函数*/
void init_stack(Link *top )
{
(*top)->next = NULL;
}
/*判断栈是否为空,由于链表,故不用判断栈满*/
int is_stack_empty(Link top)
{
if(top->next == NULL)
{
return EMPTY_OK;
}else
{
return EMPTY_NO;
}
}


/*入栈操作*/
int push_stack(Link*top,Link new_node,int num)
{
create_newnode(&new_node);
new_node->num=num+1;
    new_node->next=((*top)->next);
((*top)->next)=new_node;
return PUSH_OK;
}
/*出栈操作*/
int pop_stack(Link*top)
{
int temp;
if ( is_stack_empty(*top) == EMPTY_OK )
{
printf("the stack is empty!\n");
return POP_NO;
}
else
{
temp = (*top)->next->num;
free((*top)->next);
(*top)->next = (*top)->next->next;
return temp;
}
}


int main()
{
Link top = NULL;//定义栈指针
    Link new_node = NULL;//定义新结点
    int i;
int temp;
create_stack(&top);
init_stack(&top);




for (i=0;i<10;i++)
{
create_stack(&new_node);
is_malloc_ok(new_node);
if(push_stack(&top,new_node,i) == PUSH_OK);
{
printf("PUSH_OK\n");
}
}
for ( i = 0 ; i <= 10 ; i++ )
{
temp = pop_stack(&top);
      if(temp != POP_NO)
{
printf("%d\n",temp);
}
}






    return 0;
}
0 0
原创粉丝点击