Skip to content

Instantly share code, notes, and snippets.

@ikbear
Created July 3, 2015 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikbear/bbfb2b4917832e56beff to your computer and use it in GitHub Desktop.
Save ikbear/bbfb2b4917832e56beff to your computer and use it in GitHub Desktop.
Pop 最小值的栈
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR_DATA -999999
typedef struct {
int *pData;
int length;
int top;
} Heap_t;
void init(int *pData, int length);
void push(Heap_t *pHeap, int value);
int pop(Heap_t *pHeap);
int pop_min(Heap_t *pHeap);
void push(Heap_t *pHeap, int value){
if (pHeap->top >= pHeap->length){
fprintf(stderr, "Stack overflow");
return;
}
pHeap->pData[pHeap->top] = value;
pHeap->top++;
}
int pop(Heap_t *pHeap){
int result;
if (pHeap->top == 0){
fprintf(stderr, "Stack underflow");
return ERROR_DATA;
}
result = pHeap->pData[pHeap->top];
pHeap->top--;
return result;
}
int pop_min(Heap_t *pHeap){
int i;
int minValue = 999999;
int minIndex;
if (pHeap->top == 0){
fprintf(stderr, "Stack underflow");
return ERROR_DATA;
}
for (i=0; i<pHeap->top; i++){
if (pHeap->pData[i] < minValue){
minValue = pHeap->pData[i];
minIndex = i;
}
}
memmove(pHeap->pData + minIndex, pHeap->pData + minIndex + 1, (pHeap->top - minIndex) * sizeof(int));
pHeap->top--;
return minValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment