棧是一種數據結構,是一種只能在一端進行插入和刪除操作的特殊線性表。它按照後進先出的原則存儲數據,先進入的數據被壓入棧底,最後的數據在棧頂,需要讀數據的時候從棧頂開始彈出數據(最後一個數據被第一個讀出來)。棧具有記憶作用,對棧的插入與刪除操作中,不需要改變棧底指針。
頭文件
#pragma once
#define INITSIZE 10
typedef struct DStack
{
int *elem;//數據
int top;//棧頂指針,存放數據的下標
int stacksize;//棧的大小
}DStack , *PDStack;
void InitStack(PDStack ps);
//入棧
bool Push(PDStack ps,int val);
//獲取棧頂的值,但不刪除棧頂元素
bool GetTop(PDStack ps,int *rtval);
//出棧,獲取棧頂的值,且刪除棧頂元素
bool Pop(PDStack ps,int *rtval);
//判空
bool IsEmpty(PDStack ps);
//清棧
void Clear(PDStack ps);
//銷燬棧
void Destroy(PDStack ps);
cpp文件
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include"stack.h"
void InitStack(PDStack ps)
{
assert(ps != NULL);
if(ps == NULL)
{
return ;
}
ps->elem = (int *) malloc (INITSIZE * sizeof(int));
ps->top = 0;
ps->stacksize = INITSIZE;
}
static bool IsFull(PDStack ps)
{
return ps->top == ps->stacksize;
}
//擴容
void Inc(PDStack ps)
{
ps->elem = (int *) realloc (ps->elem,2*ps->stacksize *sizeof (int));
ps->stacksize *= 2;
}
//入棧
bool Push(PDStack ps,int val)
{
assert(ps != NULL);
if(ps == NULL)
{
return false;
}
if(IsFull(ps))
{
Inc(ps);
}
ps->elem[ps->top] = val;//!!!
ps->top ++;//!!!
return true;
}
//獲取棧頂的值,但不刪除棧頂元素
bool GetTop(PDStack ps,int *rtval)
{
assert(ps != NULL);
if(IsEmpty(ps))
{
return false;
}
if(rtval != NULL)
{
*rtval = ps->elem[ps->top-1];//!!!減一
}
return true;
}
//出棧,獲取棧頂的值,且刪除棧頂元素
bool Pop(PDStack ps,int *rtval)
{
if(IsEmpty(ps))
{
return false;
}
if(rtval != NULL)
{
*rtval = ps->elem[--ps->top];
}
return true;
}
bool IsEmpty(PDStack ps)
{
return ps->top == 0;
}
void Clear(PDStack ps)
{
ps->top = 0;
}
void Destroy(PDStack ps)
{
free(ps->elem);
ps->elem = NULL;
ps->top = 0;
ps->stacksize = 0;
}
主函數
#include<stdio.h>
#include"stack.h"
int main()
{
DStack sta;
InitStack(&sta);
int tmp;
for(int i = 0;i<10;i++)
{
Push(&sta,i+10);
}
int p =GetTop(&sta,NULL);
printf("%d\n",p);
while(!IsEmpty(&sta))
{
Pop(&sta,&tmp);
printf("%d ",tmp);
}
printf("\n");
Destroy(&sta);
return 0;
}