C++如何用链表实现栈
时间: 2024-05-06 19:19:22 浏览: 84
可以使用一个指针作为栈顶,将新元素插入到链表头,每次弹出时从头部删除。具体的实现方式可以参考以下代码:
```C
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct Stack {
Node* top;
} Stack;
void push(Stack* s, int val) {
Node* new_node = (Node*) malloc(sizeof(Node));
new_node->data = val;
new_node->next = s->top;
s->top = new_node;
}
int pop(Stack* s) {
if (s->top == NULL) {
printf("Stack is empty\n");
return -1;
}
Node* temp = s->top;
int val = temp->data;
s->top = s->top->next;
free(temp);
return val;
}
```
在主函数中,可以这样使用:
```C
int main() {
Stack s;
s.top = NULL; // 初始化栈顶指针
push(&s, 1);
push(&s, 2);
push(&s, 3);
int val = pop(&s); // val = 3
val = pop(&s); // val = 2
val = pop(&s); // val = 1
val = pop(&s); // 输出 "Stack is empty",val = -1
return 0;
}
```
阅读全文