栈类型线性表,完成创建,入栈,出栈 C语言实现,实验思路和代码
时间: 2024-06-13 21:08:35 浏览: 117
入栈出栈的C语言实现
5星 · 资源好评率100%
栈是一种常见的数据结构,可以用数组或链表实现。下面是使用链表实现栈的C语言代码,包括创建栈、入栈和出栈操作:
```c
#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;
}
// 入栈
void push(Stack *stack, int data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = stack->top;
stack->top = node;
}
// 出栈
int pop(Stack *stack) {
if (stack->top == NULL) {
printf("Stack is empty.\n");
return -1;
}
int data = stack->top->data;
Node *temp = stack->top;
stack->top = stack->top->next;
free(temp);
return data;
}
int main() {
Stack *stack = createStack();
push(stack, 1);
push(stack, 2);
push(stack, 3);
printf("%d\n", pop(stack)); // 输出:3
printf("%d\n", pop(stack)); // 输出:2
printf("%d\n", pop(stack)); // 输出:1
printf("%d\n", pop(stack)); // 输出:Stack is empty. -1
return 0;
}
```
阅读全文