c - Error in implementation of a stack with O(1) find-max/find-min? -
i have implemented several functions stack adt. trying find max , min values in o(1) time , have augmented stack structure serve purpose. code:
void mms_push(mmstack mms, int i) { struct llnode *new = malloc(sizeof(struct llnode)); new->item = i; if(mms->len!=0) { new->next = mms->topnode; mms->topnode = new; } else { new->next = null; mms->topnode = new; } if (mms->len == 0) { mms->topnode->minc = i; mms->topnode->maxc = i;} else { if(mms->topnode->maxc < i) { mms->topnode->maxc = i; } if(i<mms->topnode->minc) { mms->topnode->minc = i; } mms->len++;} int mms_pop(mmstack mms) { assert(mms); int ret = mms->topnode->item; struct llnode *backup = mms->topnode; mms->topnode = mms->topnode->next; mms->len--; free(backup); return ret; } my structures used below:
struct llnode { int item; struct llnode *next; int minc; int maxc; }; struct mmstack { int len ; struct llnode *topnode; }; typedef struct mmstack *mmstack; i not getting correct value of max , min values. how correct code right value of max , min element in stack?
thanks in advance!
take @ code:
if (mms->len == 0) { mms->topnode->minc = i; mms->topnode->maxc = i; } else { if(mms->topnode->maxc < i) { mms->topnode->maxc = i; } if(i<mms->topnode->minc) { mms->topnode->minc = i; } } notice in else branch, you're reading values of mms->topnode->minc , mms->topnode->maxc before you've initialized them. think meant @ values of mms->topnode->minc/maxc before reassigned mms->topnode. fix this, try doing this:
else { mms->topnode->maxc = mms->topnode->next->maxc; mms->topnode->minc = mms->topnode->next->minc; if(mms->topnode->maxc < i) { mms->topnode->maxc = i; } if(i<mms->topnode->minc) { mms->topnode->minc = i; } } these 2 lines initialize min , max values old max values before comparing against i, should ensure value.
hope helps!
Comments
Post a Comment