栈的链式存储也称为链栈,和链表的存储原理一样,都可以通闲散空间来存储元素,用指针来建立各节点之间的逻辑关系。同顺序栈,链表的插入,删除操作也只能在栈顶进行。
链栈的C语言实现:(codeblocks完美运行)
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data; //数据域
struct Node *next; //指向下一个节点的指针
}pNode;
typedef struct Stack
{
pNode *top; //指向栈顶元素的指针
int size; //栈的大小
}linkstack;
//初始化链栈
linkstack* create()
{
linkstack *stack = (linkstack*)malloc(sizeof(linkstack));
if(stack != NULL)
{
stack->top = NULL;
stack->size = 0;
}
return stack;
}
//判断栈是否为空,是返回1,不是返回0
int IsEmpty(linkstack *stack)
{
if(stack->top == NULL || stack->size == 0)
return 1;
return 0;
}
//获得链栈大小
int getsize(linkstack *stack)
{
return stack->size;
}
//取得栈顶元素
pNode* getTop(linkstack *stack)
{
if(stack->size != 0)
return stack->top;
return NULL;
}
//入栈
int Push(linkstack *stack,int val)
{
pNode *node = (pNode*)malloc(sizeof(pNode));
if(node != NULL)
{
node->data = val;
node->next = getTop(stack); //新元素节点指向下一个节点,链式实现
stack->top = node; //top指向新节点
stack->size++; //栈的大小加1
}
return 1;
}
//出栈
pNode* Pop(linkstack *stack)
{
if(IsEmpty(stack))
{
return NULL;
}
pNode *node = stack->top; //node指向栈顶
stack->top = stack->top->next; //top指向下一个元素
stack->size--; //链栈长度减少
return node;
}
//销毁栈
void Destroy(linkstack *stack)
{
if(IsEmpty(stack))
{
free(stack);
printf("\n链表已为空,无需再进行销毁!\n");
}
//如果链栈中数据不为空,就需要把栈中的节点都删除再释放
else
{
while(stack->size >0)
{
pNode *ptr;
ptr = Pop(stack);
free(ptr);
}
printf("链栈消除成功!\n");
}
}
int main()
{
srand((unsigned)time(0));
linkstack *stack = NULL;
stack = create();
int i;
for(i=0;i<30;i++)
Push(stack,rand()%100);
if(IsEmpty(stack))
printf("链栈为空!\n");
else
{
printf("链栈不为空!\n");
printf("栈顶元素为:%d",*((int*)getTop(stack))); //返回的是pNode类型指针,所以要强转成int型
printf("链栈大小为:%d",getsize(stack));
for(i=0;i<30;i++)
{
if(i%6==0) //每打印6个就换行
printf("\n");
printf("%3d ",*((int*)Pop(stack))); //返回的是pNode类型指针,所以要强转成int型
}
}
Destroy(stack);//销毁链
return 0;
}