您的位置:首页 > 其它

带表头结点的链表进行栈操作

2016-11-09 21:43 218 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: