我正在尝试对一个元素栈进行排序,但该函数发生了溢出,我不知道为什么会发生这种情况。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define type int //type of element in the stack
#define max 100
typedef struct {
int top;
type array[max];
} stack;
stack *initialize () {
stack *s = malloc (sizeof (stack));
s->top = 0;
return s;
}
void push (stack *s, type x) {
s->array[s->top++] = x;
}
type pop (stack *s) {
return s->array[--s->top];
}
type isfull (stack *s) {
return s->top >= max;
}
type isempty (stack *s) {
return !s->top;
}
type peek (stack *s) {
return s->array[s->top - 1];
}
void sortstack (stack *s) { //sorting the stack
stack *temp = initialize();
int x, flag;
do {
flag = 0;
while (!isempty (s)) {
x = pop (s);
if (x > peek (s)) {
push (temp, pop (s));
push (s, x);
flag = 1;
} else push (temp, x);
}
while (!isempty (temp)) push (s, pop (temp));
} while (flag);
}
int main() {
stack *s = initialize();
push (s, 2);
push (s, 4);
push (s, 4);
push (s, 7);
push (s, 9);
push (s, 18);
sortstack (s);
while (!isempty (s)) printf ("%d ", pop (s));
return 0;
}
if (x>peek(s))
时,你不知道s
上是否有任何项,因为你刚刚从s
中弹出了一个项。将其更改为if (!isempty(s) && x > peek(s))
。(你可以在你的pop
和peek
函数中包含<assert.h>
和assert(s->top > 0)
来捕获这种编程错误。另外,你的变量x
应该是type
类型的。) - M Oehm