如何实现链式存储结构的数据结构栈及c语音代码
时间: 2024-11-09 15:18:29 浏览: 19
数据结构:图解链表,用链表实现栈(c语言版)
链式存储结构的栈通常采用链表来实现,因为它不需要预先设定固定大小的内存空间。以下是使用C语言实现简单链式栈的基本步骤:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data; // 数据域
struct Node* next; // 指向下一个节点的指针
} StackNode;
// 初始化链式栈
StackNode* createStack() {
return (StackNode*)malloc(sizeof(StackNode));
}
// 入栈操作
void push(StackNode** top, int value) {
StackNode* newNode = createStack();
newNode->data = value;
newNode->next = *top;
*top = newNode;
}
// 出栈操作(如果栈不为空)
int pop(StackNode** top) {
if (*top == NULL) {
printf("Stack is empty.\n");
return -1;
}
StackNode* temp = *top;
int value = temp->data;
*top = temp->next;
free(temp);
return value;
}
// 查看栈顶元素(不会改变栈)
int peek(StackNode* top) {
if (top == NULL) {
printf("Stack is empty.\n");
return -1;
}
return top->data;
}
// 判断栈是否为空
int isEmpty(StackNode* top) {
return top == NULL;
}
int main() {
StackNode* stackTop = NULL;
push(&stackTop, 5);
push(&stackTop, 10);
push(&stackTop, 15);
printf("Top element is %d\n", peek(stackTop)); // 输出:Top element is 15
printf("%d popped from the stack\n", pop(&stackTop)); // 输出:15 popped from the stack
printf("%d popped from the stack\n", pop(&stackTop)); // 输出:10 popped from the stack
if (isEmpty(stackTop)) {
printf("Stack is now empty.\n");
} else {
printf("Stack is not empty.\n"); // 这里会输出 "Stack is not empty."
}
return 0;
}
```
阅读全文