Last active
April 27, 2017 13:06
-
-
Save pallove/1ae526aa0c1004e525674d177cb83f08 to your computer and use it in GitHub Desktop.
min value get in stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
struct tval { | |
int v; | |
int i; | |
}; | |
struct minstack { | |
int n; | |
struct tval value[0]; | |
}; | |
void push(struct minstack *s, int v) { | |
struct tval *prev = s->n ? s->value + s->n - 1 : NULL; | |
struct tval *next = s->value + s->n; | |
if (prev) { | |
int iv = s->value[prev->i].v; | |
next->i = iv > v ? s->n : prev->i; | |
} | |
else { | |
next->i = 0; | |
} | |
next->v = v; | |
++s->n; | |
} | |
int pop(struct minstack *s) { | |
--s->n; | |
return s->value[s->n].v; | |
} | |
int top(struct minstack *s) { | |
return s->value[s->n - 1].v; | |
} | |
int min(struct minstack *s) { | |
int i = s->value[s->n - 1].i; | |
return s->value[i].v; | |
} | |
int main(void) { | |
int count = 200; | |
struct minstack *stack = malloc(sizeof(struct tval) * count + sizeof(int)); | |
stack->n = 0; | |
srand((unsigned) time(NULL)); | |
for(int i = 0; i < count; i++) { | |
int v = rand() % 50; | |
printf("push %d = %d\n", i, v); | |
push(stack, v); | |
} | |
printf("get min:%d, i=%d\n", min(stack), stack->value[stack->n - 1].i); | |
free(stack); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment