c语言怎样计算栈的长度,数据结构与算法:栈 C语言实现
棧是僅在表尾進行插入、刪除操作的線性表。即棧 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;
}
測試效果:
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;
}
總結
以上是生活随笔為你收集整理的c语言怎样计算栈的长度,数据结构与算法:栈 C语言实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iPhone 14系列新配色展望:高辨识
- 下一篇: CCNA-第十四篇-NAT-下+链路聚合