栈是一种很重要的结构,它应用广泛,例如函数调用、中断、运算符操作等,本文主要记录一下栈的基本操作的C语言表达。

代码1: mystack.h

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct Element
{
int data;
struct Element *pNext;

}ELEMENT,*PELEMENT;

typedef struct Stack
{
PELEMENT pTop;
PELEMENT pBottom;
}STACK,*PSTACK;

void initStack(PSTACK ps);
void push(PSTACK ps,int value);
void pop(PSTACK ps);
void printStack(PSTACK ps);
bool isempty(PSTACK ps);

代码2:mystack.c

/*************************************************************************
* Project:
* Function: 栈的数据结构及相关操作代码

*************************************************************************
* : magc $
* : gmail.com $
*************************************************************************
*
* Copyright 2011 by magc
*
***********************************************************************
*/

#include "mystack.h"

//创建新栈

void initStack(PSTACK ps)
{
ps->pTop = (PELEMENT)malloc(sizeof(ELEMENT));
if(ps->pTop==NULL)
{
printf("内存分配失败!");
exit(-1);
}
ps->pBottom = ps->pTop;
ps->pTop->pNext = NULL;

}

//Push 压栈
void push(PSTACK ps,int value)
{
PELEMENT pe = (PELEMENT)malloc(sizeof(ELEMENT));
if( pe==NULL)
{
printf("内存分配失败!");
exit(-1);
}
pe->data = value;
pe->pNext = ps->pTop;
ps->pTop = pe;

}
//pop 出栈

void pop(PSTACK ps)
{

PELEMENT pe = ps->pTop;
ps->pTop = pe->pNext;
free(pe); //注意出栈的元素要free

}
//遍历各元素

void printStack(const PSTACK ps)
{
PELEMENT pe = ps->pTop; //要用新指针来遍历,以免改变原栈数据
while(pe!=ps->pBottom)
{
printf(" %d ",pe->data);
pe = pe->pNext;
}

}
//判断栈是否为空
bool isempty(PSTACK ps)
{
if(ps->pTop == ps->pBottom)
{
return true;
}else
return false;
}

代码3:main.c

 1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "mystack.h"
4 int main()
5 {
6 STACK s = {NULL,NULL};
7 PSTACK ps = &s ; //注意要给这个指针变量赋值
8 initStack(ps);
9 push(ps,23);
10 push(ps,33);
11 push(ps,43);
12 push(ps,53);
13 pop(ps);
14 printStack(ps);
15 printf("\n is empty %d \n",isempty(ps));
16 return 0;
17 }

 

运行结果:

 

注:此篇代码参考了郝斌老师的数据结构视频内容。