链式栈不用考虑栈空间为满的情况,不存在向上溢出。
Linux上编译有个warning说的是int 和 void*之间的转换,而事实上在32bits机器上这两者之间是可以相互转换的,而测试在64bits系统上就会存在这个提示。不知道大家有什么好的解决办法?
实现代码如下:
头文件:
#ifndef LINK_STACK_H_INCLUDED
#define LINK_H_INCLUDED
typedef void* Element;
// top points to the top node of the stack
typedef struct l_stack_node
{
Element data;
struct l_stack_node *next;
}l_stack_node, *lnode;
typedef struct l_stack
{
l_stack_node* top;
int count;
}l_stack, *pstack;
pstack init_stack();
lnode init_lnode();
int is_empty(pstack ps);
Element get_top(pstack ps);
Element pop(pstack ps);
pstack push(pstack ps, Element e);
void display_stack(pstack ps);
#endif // LINK_STACK_H_INCLUDED
实现文件:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "link_stack.h"
#define TRUE 0
#define FALSE 1
pstack init_stack()
{
pstack ps;
if((ps = (pstack)malloc(sizeof(l_stack))) == NULL){
printf("Init link stack error\n");
return NULL;
}
ps->top = NULL;
ps->count = 0;
return ps;
}
lnode init_lnode()
{
lnode node;
if((node = (lnode)malloc(sizeof(l_stack_node))) == NULL){
printf("Init link node error\n");
}
node->next = NULL;
// if node points to NULL then return NULL
return node;
}
int is_empty(pstack ps)
{
return ((ps->count <= 0)?TRUE : FALSE);
}
Element get_top(pstack ps)
{
if(is_empty(ps) == 0)
{
printf("Link stack is empty\n");
return NULL;
}
else
return ps->top->data;
}
int get_count(pstack ps)
{
if(ps != NULL)
return ps->count;
else
return 0;
}
Element pop(pstack ps)
{
if(ps->count <= 0)
return NULL;
lnode n = ps->top;
ps->top = n->next;
ps->count--;
return n->data;
}
pstack push(pstack ps, Element e)
{
lnode node = init_lnode();
node->data = e;
node->next = ps->top;
ps->top = node;
ps->count++;
return ps;
}
void display_stack(pstack ps)
{
lnode t = ps->top;
if(is_empty(ps) == 0)
printf("Link stack is empty\n");
else
{
while(t != NULL)
{
printf("%d ", t->data);
t = t->next;
}
printf("\n");
}
}
测试文件:
#include <stdio.h>
#include <stdlib.h>
#include "link_stack.h"
int main()
{
int i;
int arr[] = {1,2,3,4,5,6,7,8};
int len = 8;
pstack ps = init_stack();
for(i=0; i<len; i++)
ps = push(ps, arr[i]);
display_stack(ps);
int n = pop(ps);
display_stack(ps);
return 0;
}