Created
July 3, 2015 05:01
-
-
Save ikbear/bbfb2b4917832e56beff to your computer and use it in GitHub Desktop.
Pop 最小值的栈
This file contains 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 <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