用栈火车进出站c语言代码
时间: 2024-06-14 21:02:52 浏览: 10
在C语言中,我们可以使用数组或链表来模拟栈(先进后出,LIFO)的数据结构,用来模拟火车进站和出站的过程。这里是一个简单的链表实现的栈火车进出站的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义栈节点结构
typedef struct Node {
int value;
struct Node* next;
} StackNode;
// 初始化栈
StackNode* createStack() {
StackNode* top = (StackNode*)malloc(sizeof(StackNode));
if (top) {
top->value = 0; // 初始化栈顶元素
top->next = NULL;
}
return top;
}
// 入栈
void push(StackNode** top, int value) {
StackNode* newNode = (StackNode*)malloc(sizeof(StackNode));
if (newNode) {
newNode->value = value;
newNode->next = *top;
*top = newNode;
} else {
printf("Memory allocation failed!\n");
}
}
// 出栈
int pop(StackNode** top) {
if (*top == NULL) {
printf("Stack is empty.\n");
return -1;
} else {
int value = (*top)->value;
StackNode* temp = *top;
*top = (*top)->next;
free(temp);
return value;
}
}
// 模拟火车进站(入栈)
void trainEnter(int trainNumber, StackNode** top) {
printf("Train %d entering the station.\n", trainNumber);
push(top, trainNumber);
}
// 模拟火车出站(出栈)
void trainLeave(StackNode** top) {
int trainNumber = pop(top);
if (trainNumber != -1) {
printf("Train %d has left the station.\n", trainNumber);
}
}
int main() {
StackNode* top = createStack();
// 示例操作
trainEnter(101, &top);
trainEnter(202, &top);
trainLeave(&top);
trainLeave(&top);
return 0;
}
```
在这个例子中,我们定义了一个栈结构,并实现了入栈(push)、出栈(pop)以及模拟火车进站(trainEnter)和出站(trainLeave)的操作。火车进站是将车次压入栈顶,火车出站则是从栈顶取出车次。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)