#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//链式栈需要先进后出,采用头插法,每次取出数据后就删除此节点
//无头链表比较适用
typedef struct Node
{
int data;
struct Node* next;
}NODE ,*LPNODE;
typedef struct
{
LPNODE stackTop;
int curSize;
}STACK ,*LPSTACK;
//创建结构的函数返回创建的事物的地址(结构等不加&),创建结构函数的返回值需要与结构类型相同
LPNODE createNode(int data)
{
LPNODE newNode = (LPNODE)malloc(sizeof(NODE));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
LPSTACK createStack()
{
LPSTACK pstack = (LPSTACK)malloc(sizeof(STACK));
assert(pstack);
pstack->curSize = 0;
pstack->stackTop = NULL;
return pstack;
}
void push(LPSTACK pstack,int data)//入栈
{
LPNODE newNode = createNode(data);
if (pstack->curSize == 0)
{
pstack->stackTop = newNode;
}
else
{
newNode->next = pstack->stackTop; //新节点连接老节点(新节点指针域指向原栈顶指针的地址,新节点放老节点前面)
pstack->stackTop = newNode; //栈顶指针改为指向新节点
}
pstack->curSize++;
}
int size(LPSTACK pstack) //确定栈数据个数
{
return pstack->curSize;
}
int empty(LPSTACK pstcak) //判定是否栈空
{
return pstcak->curSize == 0;
}
int top(LPSTACK pstack)//获取栈顶元素
{
if (pstack == NULL || pstack->curSize == 0)
{
printf("栈空,无法获取栈顶元素\n");
printf("\n");
return 0;
}
return pstack->stackTop->data;
}
//出栈
int pop(LPSTACK pstack)
{
if (pstack == NULL || pstack->curSize == 0)
{
printf("栈空,无法出栈元素\n");
printf("\n");
return 0;
}
LPNODE nextNode = pstack->stackTop->next; //删除原头部前先保存原头部的下一个地址,在删除原头部后作为新头部,由头部指针指向
free(pstack->stackTop);
pstack->stackTop = nextNode;
pstack->curSize--;
return pstack->stackTop->data;
}
int main()
{
LPSTACK pstack = createStack(); //调用创建新链表栈的函数
for (int i = 0; i < 5; i++)
{
push(pstack, i);
}
while (pstack)
{
pop(pstack);
printf("%d\t",pstack->stackTop->data);
}
return 0;
}
C语言链式栈
最新推荐文章于 2024-06-05 16:55:53 发布