C语言top指针指向栈顶元素的下一个位置读取栈顶元素
要读取栈顶元素,可以使用*(top-1)来获取栈顶元素的值。下面是一个示例代码:
#include <stdio.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int* top = stack; // top指针指向栈顶元素的下一个位置
void push(int value) {
if (top - stack < MAX_SIZE) {
*top = value;
top++;
} else {
printf("Stack Overflow\n");
}
}
int pop() {
if (top == stack) {
printf("Stack Underflow\n");
return -1;
} else {
top--;
return *top;
}
}
int peek() {
if (top == stack) {
printf("Stack is Empty\n");
return -1;
} else {
return *(top - 1);
}
}
int main() {
push(1);
push(2);
push(3);
printf("Stack top element: %d\n", peek());
pop();
printf("Stack top element after popping: %d\n", peek());
return 0;
}
输出结果:
Stack top element: 3
Stack top element after popping: 2
在这个例子中,我们使用push函数将元素1、2和3依次入栈,然后使用peek函数读取栈顶元素的值,再使用pop函数将栈顶元素出栈,最后再次使用peek函数读取栈顶元素的值
原文地址: https://www.cveoy.top/t/topic/iIon 著作权归作者所有。请勿转载和采集!