#include <head.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node* next;
} Node;
typedef struct Stack
{
Node* top;
} Stack;
// 创建
Stack* createStack()
{
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = NULL;
return stack;
}
// 判断栈是否为空
int isEmpty(Stack* stack)
{
return (stack->top == NULL);
}
// 入栈
void push(Stack* stack, int data)
{
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = stack->top;
stack->top = newNode;
}
// 出栈
int pop(Stack* stack)
{
if (isEmpty(stack))
{
printf("栈已空,无法出栈!\n");
return -1; // 返回一个特定值表示出错
}
Node* temp = stack->top;
int data = temp->data;
stack->top = stack->top->next;
free(temp);
return data;
}
// 访问栈顶元素
int peek(Stack* stack)
{
if (isEmpty(stack))
{
printf("栈为空!\n");
return -1; // 返回一个特定值表示出错
}
return stack->top->data;
}
// 打印栈中的元素
void printStack(Stack* stack)
{
if (isEmpty(stack))
{
printf("栈为空!\n");
return;
}
printf("栈中的元素为:");
Node* current = stack->top;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main(int argc, const char *argv[])
{
Stack* stack = createStack();
push(stack, 10);
push(stack, 20);
push(stack, 30);
push(stack, 40);
printf("栈顶元素为:%d\n", peek(stack));
printStack(stack);
pop(stack);
printf("栈顶元素为:%d\n", peek(stack));
printStack(stack);
free(stack); // 释放内存
return 0;
}
10.5:实现链栈的代码
最新推荐文章于 2024-11-02 15:25:13 发布