c语言怎样计算栈的长度,数据结构与算法:栈 C语言实现

本文介绍了如何使用C语言实现顺序栈和链栈。通过定义数据结构和相应的压栈、出栈操作,展示了栈的“后进先出”特性。顺序栈使用数组存储,链栈则使用链表。提供了示例代码并进行了测试,帮助理解栈的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

栈是仅在表尾进行插入、删除操作的线性表。即栈 S= (a1, a2, a3, ………,an-1, an),其中表尾称为栈顶 /top,表头称为栈底/base。

由于只能在表尾进行操作,因此栈的运算规则就是“后进先出”(LIFO)

和线性表类似,栈也有两种存储结构——顺序栈与链栈

1.顺序栈的C语言实现#include

#include

typedef struct Stack {

int *data;//数据域

int size;//栈长度,也是栈顶数组下标-1

int max;//栈最大容量

} Stack;

//初始化

Stack *initStack(int max)

{

struct Stack *stack;

stack = (struct Stack *)malloc(sizeof(struct Stack));

stack->size = 0;

stack->max = max;

stack->data = (int*)malloc(sizeof(int)*max);

return stack;

}

//压栈

void push(Stack *stack, int item)

{

if (stack->size >= stack->max)

{

printf("stack is full! \n");

}else{

stack->data[stack->size++] = item;

}

}

//出栈

int pop(Stack *stack)

{

if (stack->size >= 0)

{

return stack->data[--stack->size];

}

}

//test

int main()

{

struct Stack *stack;

stack = initStack(3);

push(stack,1);

push(stack,2);

push(stack,3);

push(stack,4);

printf("stack out:%d \n", pop(stack));

printf("stack out:%d \n", pop(stack));

push(stack,5);

push(stack,6);

push(stack,7);

printf("stack out:%d \n", pop(stack));

printf("stack out:%d \n", pop(stack));

printf("stack out:%d \n", pop(stack));

return 0;

}

测试效果:

bVcIyMn

2.链栈的C语言实现

本想偷懒,算了,还是写一遍吧,区别只是用链表去代替了数组,其实还不如数组方便省事一。一,但是可以无限长,,,#include

#include

typedef struct StackNode {

int data;//数据域

struct StackNode *next;//指针域,这里用next或者pre都行,看怎么规定左右了,如果是左进左出那就是next,右进右出就是pre好理解

} StackNode;

typedef struct LinkedStack {

int size;//栈长度

int max;//栈最大容量

struct StackNode *top;//指针域

} LinkedStack;

//初始化

LinkedStack *initStack(int max)

{

struct LinkedStack *stack;

stack = (struct LinkedStack *)malloc(sizeof(struct LinkedStack));

stack->size = 0;

stack->max = max;

stack->top = NULL;

return stack;

}

//压栈

void push(LinkedStack *stack, int item)

{

if (stack->size >= stack->max)

{

printf("stack is full! \n");

}else{

struct StackNode *node;

node = (struct StackNode *)malloc(sizeof(struct StackNode));

node->data = item;

node->next = stack->top;

stack->size++;

stack->top = node;

}

}

//出栈

int pop(LinkedStack *stack)

{

if (stack->size > 0)

{

struct StackNode *top;

top = stack->top;

stack->top = top->next;

stack->size--;

return top->data;

}

}

int main()

{

struct LinkedStack *stack;

stack = initStack(3);

push(stack,1);

push(stack,2);

push(stack,3);

push(stack,4);

printf("stack out:%d \n", pop(stack));

printf("stack out:%d \n", pop(stack));

push(stack,5);

push(stack,6);

push(stack,7);

printf("stack out:%d \n", pop(stack));

printf("stack out:%d \n", pop(stack));

printf("stack out:%d \n", pop(stack));

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值