用c语言设计一个算法求战内元素最小值。声明两个栈,栈1放数据元素,栈2放栈1内数据 元素的最小值,栈1元素依次出栈,栈2显示栈1剩余元素最小值。
时间: 2024-05-01 20:16:58 浏览: 14
以下是使用C语言实现的算法:
```
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 100
typedef struct Stack {
int top;
int data[STACK_SIZE];
} Stack;
void push(Stack *s, int x) {
if (s->top < STACK_SIZE) {
s->data[++s->top] = x;
}
}
int pop(Stack *s) {
if (s->top >= 0) {
return s->data[s->top--];
}
return -1;
}
int min(Stack *s) {
int min = s->data[s->top];
for (int i = s->top; i >= 0; i--) {
if (s->data[i] < min) {
min = s->data[i];
}
}
return min;
}
int main() {
Stack s1, s2;
s1.top = -1;
s2.top = -1;
// 测试数据
push(&s1, 5);
push(&s1, 2);
push(&s1, 4);
push(&s1, 1);
push(&s1, 3);
// 计算s1中的最小值并入栈s2
while (s1.top >= 0) {
int x = pop(&s1);
push(&s2, x);
push(&s2, min(&s1));
}
// 弹出s2中的最小值
printf("The minimum value in s1 is %d\n", pop(&s2));
return 0;
}
```
该算法使用了两个栈s1和s2,s1用于存储数据元素,s2用于存储s1中剩余元素的最小值。算法的思路是,将s1中所有元素逐个弹出并入栈s2,同时将s1中弹出元素之前的最小值入栈s2。这样,栈s2的栈顶就是s1中所有元素的最小值,直接弹出即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)