写一个栈的基本操作C++代码
时间: 2023-06-01 15:06:42 浏览: 76
栈的基本操作(C++)
当然,我可以提供给你一个栈的基本操作C代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct stack {
int data;
struct stack* next;
} Stack;
Stack* top = NULL;
void push(int data) {
Stack* new_node = (Stack*)malloc(sizeof(Stack));
if(new_node == NULL) {
printf("Out of memory!\n");
return;
}
new_node->data = data;
new_node->next = top;
top = new_node;
}
int pop() {
if(top == NULL) {
printf("Stack is empty!\n");
return -1;
}
int data = top->data;
Stack* temp = top;
top = top->next;
free(temp);
return data;
}
int main() {
push(1);
push(2);
push(3);
printf("%d\n", pop()); // should print 3
printf("%d\n", pop()); // should print 2
printf("%d\n", pop()); // should print 1
printf("%d\n", pop()); // should print "Stack is empty!"
return 0;
}
阅读全文