(栈和堆对比:堆空间由程序员申请和释放)
一、顺序栈
代码实现:
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <strings.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
ypedef struct seq_stack //用于管理顺序栈的数据类型
{
int * ps;//顺序栈的起始地址
int len;//表示能够存储的数据节点的个数
int cnt;//已经使用了的表项个数
}ST,*PST;
PST init_seq_stack(int length)//初始化一个空的顺序栈
{
PST p = malloc(sizeof(ST));
if(p == NULL)
return p;
p->ps = malloc(sizeof(int)*length);
if(p->ps == NULL)
{
printf("malloc failed!\n");
free(p);
return NULL;
}
p->len = length;
p->cnt = 0;
return p;
}
bool is_full(PST p)
{
if(p->cnt == p->len)
return true;
else
return false;
}
bool is_empty(PST p)
{
if(p->cnt == 0)
return true;
else
return false;
}
bool push(PST p,int data)//入栈
{
int i;
if(is_full(p))
return false;
p->ps[p->cnt] = data;
p->cnt++;
return true;
}
bool pop(PST p,int *pdata)
{
int i;
if(is_empty(p))
{
printf("is empty\n");
return false;
}
*pdata = p->ps[p->cnt-1];
p->cnt--;
return true;
}
void show_seq_stack(PST p)
{
int i;
if(is_empty(p))
{
printf("is empty\n");
return;
}
for(i = ((p->cnt) -1);i>=0;i--)
printf("%d\t",p->ps[i]);
printf("\n");
}
int main(int argc,char *argv[])
{
PST p;
p = init_seq_stack(5);
push(p,1);
push(p,2);
push(p,3);
push(p,4);
push(p,5);
if(push(p,6))
printf("push ok\n");
else
printf("push bu ok\n");
show_seq_stack(p);
return 0;
}
二、链式栈:
代码实现
typedef struct node
{
int data;//数据域
struct node *next;
}NODE,*PNODE;
typedef struct stack//管理链式栈的数据类型
{
PNODE pbot;
PNODE ptop;
}ST,*PST;
PST init_link_stack(void)
{
PST p = malloc(sizeof(ST));
if(p == NULL)
{
//exit(-1);
return p;
}
p->ptop = malloc(sizeof(NODE));
if(p->ptop == NULL)
{
//exit(-1);
free(p);
return NULL;
}
p->pbot = p->ptop ;
p->ptop->next = NULL;
return p;
}
bool push(PST ps,int dat)
{
PNODE pnew = malloc(sizeof(NODE));
if(pnew == NULL)
return false;
pnew->data = dat;
pnew->next = NULL;
ps->ptop->next = pnew;
ps->ptop = pnew;
return true;
}
bool is_empty(PST ps)
{
if(ps->ptop == ps->pbot)
return true;
else
return false;
}
bool pop(PST ps,int * pdata)
{
if(is_empty(ps))
return false;
*pdata = ps->ptop->data;
PNODE p = ps->pbot;
while(p->next != ps->ptop )
{
p = p->next;
}
ps->ptop = p;
free(p->next);
ps->ptop->next = NULL;
return true;
}
void show_stack(PST ps)
{
PNODE p = NULL;
if(is_empty(ps))
{
printf("stack is empty!\n");
return;
}
PNODE ptmp = ps->ptop;
while(ptmp != ps->pbot)
{
PNODE p = ps->pbot;
while(p->next != ptmp )
{
p = p->next;
}
printf("%d\t",ptmp->data);
ptmp = p;
}
printf("\n");
}
int main(int argc,char *argv[])
{
PST ps;
int dat;
ps = init_link_stack();
push(ps,1);
push(ps,2);
push(ps,3);
push(ps,4);
show_stack(ps);
pop(ps,&dat);
show_stack(ps);
return 0;
}