练习 #2
Coddy 栈:数据结构系列 #1 课程的第 10 课,共 13 课。
接下来的挑战需要用到 栈 。
已经为你提供了 Stack 数据结构,使用它吧!
挑战
简单编写一个函数 nse,接收一个整数数组,并返回一个数组,其中包含每个元素左侧最近的较小元素。如果某个元素左侧没有较小元素,则返回 -1。
使用提供的 Stack 来解决这个问题!
示例:
输入:[4, 5, 2, 10, 8]
预期输出:[-1, 4, -1, 2, 2]
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include "nse.h"
int main() {
int* a = (int*)malloc(sizeof(int) * 1000);
int aSize = 0;
int x;
while (scanf("%d", &x) == 1) {
a[aSize++] = x;
}
int returnSize;
int* result = nse(a, aSize, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d\n", result[i]);
}
free(a);
return 0;
}
栈:数据结构系列 #1中的所有课
自己练习: C 在线编译器