c++写一个链栈并输出
时间: 2024-05-07 14:16:34 浏览: 13
好的,这是一个简单的链栈的实现:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
typedef struct Stack{
Node* top;
}Stack;
void init(Stack* s){
s->top = NULL;
}
void push(Stack* s, int data){
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = s->top;
s->top = node;
}
int pop(Stack* s){
if(s->top == NULL){
printf("Stack is empty!\n");
return -1;
}
Node* node = s->top;
s->top = s->top->next;
int data = node->data;
free(node);
return data;
}
void print(Stack* s){
if(s->top == NULL){
printf("Stack is empty!\n");
return;
}
Node* node = s->top;
printf("Stack: ");
while(node != NULL){
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main(){
Stack s;
init(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
push(&s, 4);
print(&s);
printf("pop: %d\n", pop(&s));
printf("pop: %d\n", pop(&s));
print(&s);
return 0;
}
```
希望能对你有所帮助!现在,让我来讲个笑话吧:为什么小明的作业总是被老师批得很差?因为他总是用钢笔写作业,而老师用铅笔批改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)