/************************************************************************/
/* 栈的链式存储 */
/************************************************************************/
#include <STDIO.H>
#include <STDLIB.H>
#define STACK_INIT_SIZE 100//栈的初始大小
#define _OK 1
#define _ERROR 0
typedef int SELemType;
typedef int Status;
struct Node;
typedef struct Node* PTNode;
//链表节点
struct Node
{
PTNode next;
SELemType data;
};
/*
栈的数据抽象
*/
typedef struct
{
PTNode top;//栈顶指针,指向栈顶元素的下一个内存空间
int stacksize;//栈的大小
}LkStack;
//初始化栈
void InitStack(LkStack &L)
{
L.top = (PTNode)malloc(sizeof(Node));
L.top->data=NULL;
L.top->next=NULL;
L.stacksize = 0;
}
/*判断栈中的元素是否为空*/
bool IsEmpty(LkStack L)
{
if(L.top->next==NULL)
return true;
return false;
}
/*入栈操作*/
Status Push(LkStack &L,SELemType e)
{
PTNode newElement = (PTNode)malloc(sizeof(Node));
if (newElement==NULL)
return _ERROR;
//插入操作
newElement->data=e;
newElement->next=L.top->next;
L.top->next=newElement;
L.stacksize++;
return _OK;
}
/*出栈操作*/
Status Pop(LkStack &L,SELemType &e)
{
if(IsEmpty(L))
return _ERROR;//表明栈已经空
//出栈
PTNode temp = L.top->next;
L.top->next=temp->next;
e = temp->data;
free(temp);//释放空间
L.stacksize--;
return _OK;
}
/*取栈顶元素*/
Status GetTop(LkStack &L,SELemType &e)
{
if(!IsEmpty(L))//如果栈不为空
e=L.top->next->data;
return _OK;
}
int GetStackSize(LkStack L)
{
return L.stacksize;
}
/*打印栈中的元素*/
void PrintStack(LkStack L)
{
PTNode temp = L.top;
while(temp->next!=NULL)
{
printf("%d \n",temp->next->data);
temp=temp->next;
}
}
void main()
{
//初始化一个栈
LkStack lkstack;
InitStack(lkstack);
//向栈中压入元素
Push(lkstack,0);
Push(lkstack,1);
Push(lkstack,2);
Push(lkstack,3);
Push(lkstack,4);
Push(lkstack,5);
//打印栈中的数据
PrintStack(lkstack);
SELemType e;
Pop(lkstack,e);
printf("弹出%d\n",e);
Pop(lkstack,e);
printf("弹出%d\n",e);
//打印栈中的数据
PrintStack(lkstack);
printf("size is %d\n",lkstack.stacksize);
}