下面是 C 语言中链接堆栈的实现和表示:
'''c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Stack {
struct Node* top;
};
void initializeStack(struct Stack* stack) {
stack->top = NULL;
}
int isStackEmpty(struct Stack* stack) {
return stack->top == NULL;
}
void push(struct Stack* stack, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = stack->top;
stack->top = newNode;
}
int pop(struct Stack* stack) {
if (isStackEmpty(stack)) {
printf("Stack Underflow\n");
return -1;
}
struct Node* temp = stack->top;
int value = temp->data;
stack->top = temp->next;
free(temp);
return value;
}
int peek(struct Stack* stack) {
if (isStackEmpty(stack)) {
printf("Stack is Empty\n");
return -1;
}
return stack->top->data;
}
void displayStack(struct Stack* stack) {
if (isStackEmpty(stack)) {
printf("Stack is Empty\n");
return;
}
printf("Stack: ");
struct Node* current = stack->top;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Stack stack;
initializeStack(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
push(&stack, 40);
displayStack(&stack);
printf("Top element: %d\n", peek(&stack));
int poppedElement = pop(&stack);
printf("Popped element: %d\n", poppedElement);
displayStack(&stack);
return 0;
}
'''
在此实现中,我们定义了一个“节点”结构,该结构表示链接堆栈中的节点。每个节点都包含一个整数“data”来存储值,以及一个指针“next”来指向堆栈中的下一个节点。
“Stack”结构表示链接的堆栈,并包含指向堆栈顶部节点的指针“top”。如果堆栈为空,则“top”设置为“NULL”。
“initializeStack”函数通过将“top”设置为“NULL”来初始化堆栈。“isStackEmpty”函数通过验证“top”是否为“NULL”来检查堆栈是否为空。
“push”函数将元素插入堆栈中。它创建一个新节点,将值分配给“data”,并使新节点的“next”指针指向当前顶部节点。然后,它会更新“top”以指向新节点。
'pop' 函数删除并返回堆栈的顶部元素。它检查堆栈是否为空,并在这种情况下返回 -1。否则,它将顶部节点存储在临时变量“temp”中,从“temp->data”中检索值,将“top”更新为指向下一个节点,并释放“temp”占用的内存。
“peek”函数返回顶部元素的值,而不将其删除。它检查堆栈是否为空,并在这种情况下返回 -1。否则,它将从“top->data”中检索值。
'displayStack' 函数从上到下打印堆栈的元素。它从“top”开始遍历堆栈并打印每个节点的值。
在“main”函数中,我们初始化一个堆栈并执行一些堆栈操作来演示功能。我们使用“push”函数插入元素,“peek”函数检索顶部元素,“pop”函数删除元素,使用“displayStack”函数打印堆栈的内容。
此实现表示一个链接堆栈,其中节点通过指针动态分配和连接,从而允许有效地插入和删除元素。