链式栈
链式栈是一种数据存储结构,可以通过单链表的方式来实现,使用链式栈的优点在于它能够克服用数组实现的顺序栈空间利用率不高的特点,但是需要为每个栈元素分配额外的指针空间用来存放指针域。
链式栈实现函数举例如下:
typedef int datatype;
typedef struct node{
datatype data;
struct node *next;
}listnode, *linklist;
linklist linkstack_create();
int linkstack_empty(linklist s);
void linkstack_clear(linklist s);
int linkstack_push(linklist s, datatype value);
datatype linkstack_pop(linklist s);
datatype linkstack_top(linklist s);
void linkstack_free(linklist s);
linklist linkstack_create()
{
linklist s;
if((s = (linklist)malloc(sizeof(listnode))) == NULL){
printf("malloc failed\n");
return NULL;
}
s->next = NULL;
return s;
}
int linkstack_empty(linklist s)
{
return (s->next == NULL ? 1 : 0);
}
void linkstack_clear(linklist s)
{
linklist p;
p = s->next;
while(p)
{
s->next = p->next;
printf("%$d", p->data);
free(p);
p = s->next;
}
}
int linkstack_push(linklist s, datatype value)
{
linklist p;
if((p = (linklist)malloc(sizeof(listnode))) == NULL){
printf("malloc failed\n");
return -1;
}
p->data value;
p->next = s->next;
s->next = p;
return 0;
}
datatype linkstack_pop(linklist s)
{
linklist p;
int ret = 0;
p = s->next;
s->next = p->next;
ret = p->data;
free(p);
p = NULL;
return ret;
}
datatype linkstack_top(linklist s)
{
return (s->next->data);
}
void linklist_free(linklist s)
{
linklist p;
while(p){
s = s->next;
printf("%d", p->data);
free(p);
p = s;
}
puts("");
}
int main(int argc, const char *argv[])
{
linklist s;
int n = 10;
s = linkstack_create();
linkstack_push(s,10);
linkstack_push(s,20);
linkstack_push(s,30);
linkstack_push(s,40);
while(!linkstack_empty(s))
{
printf("%d",linkstack_pop(s));
}
puts("");
return 0;
linkstack_free(s);
}