顺序栈实现
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#define INIT_SIZE 10
typedef struct Stack
{
int* base;//指向动态内存
int stackSize;//栈的总大小
int top;//栈顶指针,实际为下标
}Stack,*PStack;
//初始化
void InitStack(PStack ps)
{
assert(ps!=NULL);
if(ps == NULL)
return;
ps->base = (int*)malloc(INIT_SIZE *sizeof(int));
assert(ps->base!=NULL);
ps->stackSize = INIT_SIZE;
ps->top = 0;
}
bool IsEmpty(PStack ps)
{
return ps->top == 0;
}
bool IsFull(PStack ps)
{
return ps->top == ps->stackSize;
}
//获取有效数据元素个数
int GetLength(PStack ps)
{
return ps->top;
}
//扩容
void Inc(PStack ps)
{
ps->stackSize *= 2;
ps->base = (int*)realloc(ps->base,ps->stackSize *sizeof(int));
assert(ps->base != NULL);
}
//入栈
bool Push(PStack ps,int val)
{
if(IsFull(ps))
Inc(ps);
ps->base[ps->top++] = val;
return true;
}
//出栈
bool Pop(PStack ps,int* rtval)
{
if(IsEmpty(ps))
return false;
*rtval = ps->base[--ps->top];
return true;
}
//获取栈顶元素的值,但不删除
int GetTop(PStack ps,int* rtval)
{
if(IsEmpty(ps))
return false;
*rtval = ps->base[ps->top-1];
return true;
}
void Destroy(PStack ps)
{
free(ps->base);
ps->base = NULL;
ps->top = 0;
ps->stackSize = 0;
}
int main()
{
Stack s;
InitStack (&s);
for(int i = 0;i<13;i++)
{
Push(&s,i);
}
int val;
for(int i = 0;i<20;i++)
{
if(Pop(&s,&val))
printf("%d ",val);
else
break;
}
Destroy(&s);
}
链式栈实现
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef struct LSNode
{
int data;
struct LSNode *next;
}LSNode,*PLStack;
//初始化
void InitStack(PLStack ps)
{
assert(ps!=NULL);
if(ps == NULL)
return;
ps->next = NULL;
}
//判空
bool IsEmpty(PLStack ps)
{
return ps->next == NULL;
}
//获取有效数据元素
int GetLength(PLStack ps)
{
int count = 0;
LSNode* q = ps->next;
while(q != NULL)
{
count++;
q = q->next;
}
return count;
}
//入栈
bool Push(PLStack ps,int val)
{
LSNode* pnewnode = (LSNode*)malloc(sizeof(LSNode));
pnewnode->data = val;
pnewnode->next = NULL;
pnewnode->next = ps->next;
ps->next = pnewnode;
return true;
}
//获取栈顶元素的值,但不删除
bool GetTop(PLStack ps,int *rtval)
{
if(IsEmpty(ps))
return false;
*rtval = ps->next->data;
return true;
}
//出栈
bool Pop(PLStack ps,int *rtval)
{
if(IsEmpty(ps))
return false;
*rtval = ps->next->data;
LSNode* q = ps->next;
ps->next = q->next;
free(q);
return true;
}
//销毁
void Destroy(PLStack ps)
{
if(ps == NULL||ps->next == NULL)
return;
LSNode* pCur;
while(ps->next != NULL)
{
pCur = ps->next;
ps->next = pCur->next;
free(pCur);
}
}
int main()
{
LSNode head;
InitStack (&head);
for(int i = 0;i<10;i++)
{
Push(&head,i);
}
printf("%d\n",GetLength(&head));
int rtval;
for(int i = 0;i<20;i++)
{
if(Pop(&head,&rtval))
{
printf("%d ",rtval);
}
else
{
break;
}
}
return 0;
}
311

被折叠的 条评论
为什么被折叠?



