void RBDestroy(RBTree* tree){ Stack* stack = (Stack*)malloc(sizeof(Stack)); stackCreate(stack, 16); RBNode* current = tree->nil; do{ if(!stackEmpty(stack)){ current = stackTop(stack); stackPop(stack); }else{ current = tree->root; } if(current->right != tree->nil){ stackPush(stack, current->right); } if(current->left != tree->nil){ stackPush(stack, current->left); } free(current); }while(!stackEmpty(stack)); stackDestroy(stack); free(stack); free(tree->root); free(tree->nil); free(tree); }
/* ** Pomocná funkce doOperation. ** Zpracuje operátor, který je pøedán parametrem c po naètení znaku ze ** vstupního pole znakù. ** ** Dle priority pøedaného operátoru a pøípadnì priority operátoru na ** vrcholu zásobníku rozhodneme o dal¹ím postupu. Délka pøevedeného ** výrazu a takté¾ ukazatel na první volné místo, do kterého se má zapisovat, ** pøedstavuje parametr postLen, výstupním polem znakù je opìt postExpr. */ void doOperation ( tStack* s, char c, char* postExpr, unsigned* postLen ) { char topChar; if (!stackEmpty(s)) { // nacteni znaku z vrcholu zasobniku pokud neni zasobnik prazdny stackTop(s, &topChar); } // Operátor vkladam na vrchol zasobniku v pripade, ze: // - zásobník je prázdný // - na vrcholu zásobníku je levá závorka // - na vrcholu zásobníku je operátor s ni¾¹í prioritou if ( (stackEmpty(s)) || (topChar == '(') || (topChar == '+' && c != '-' && c != '+') || (topChar == '-' && c != '-' && c != '+') ) { // nacteni operatoru do zasobniku stackPush(s, c); } else { postExpr[*postLen] = topChar; *postLen+=1; stackPop(s); doOperation(s, c, postExpr, postLen); } }
void verificarExpresion(char** cad){ String cadena = *cad; int length = strlen(cadena); /** Auxiliares para continuar con el ciclo*/ int i = 0; StackEntry op1, op2, res; int posError; bool evalacion = true; /** Pila para el evaluador */ ptrNodoPila pila = NULL; while(cadena[i] != '\0' && evalacion == true){ /** Validamos si se trata de un operando */ if(esOperando(cadena[i])){ int aux = cadena[i] -'0'; push(&pila,aux); } else /**Validamos si es un operador */ if (esOperador(cadena[i])){ /** Valida si existen al menos dos operandos */ if(!stackEmpty(&pila)){ op2 = pop(&pila); if (!stackEmpty(&pila)){ op1 = pop(&pila); res = calcular(op1, cadena[i], op2); push(&pila,res); }else{ printf("\nSe esperaba un operando antes del operador %c en lo posicion %d\n",cadena[i],i+1); break; } }else{ printf("\nSe esperaban dos operandos antes del operador %c en lo posicion %d\n",cadena[i],i+1); break; } }else{ printf("Caracter invalido en la posicion %d\n",i+1); break; } /** Valida que haya quedado solo un numero en la pila */ i++; } if(!stackEmpty(&pila)){ res = pop (&pila); if(stackEmpty(&pila)) printf("\n<<< Expresion posfija valida!>>>\n<<< Resultado final:\t%d>>>\n",res); else printf("\n>>> Se esperaban mas operadores\n"); } }
/* ** This nonrecursive implementation of quicksort uses an explicit ** stack, replacing recursive calls with stack pushes(of the parameters) ** and pops, until the stack is empty. We put the larger of the two subfiles ** on the stack first to ensure the maximum stack depth for sorting N ** elements is lgN. */ void quick_sort(item_t *array,int left,int right) { int i; int l,r; stackInit(right-left+1); stackPush(right); stackPush(left); while(!stackEmpty()){ l=stackPop(); r=stackPop(); if(r<=l) continue; i=partition(array,l,r); if(i-l > r-i){ stackPush(i-1); stackPush(l); stackPush(r); stackPush(i+1); }else{ stackPush(r); stackPush(i+1); stackPush(i-1); stackPush(l); } } }
void main(void) { int k; Queue* q = qCreate(10); for (int i = 0; i < 16; ++i) { qEnqueue(q, i); } while (!qEmpty(q)) { printf("%d ", qDequeue(q)); printf(" (size left = %d)\n", qSize(q)); } for (int i = 0; i < 16; ++i) { qEnqueue(q, i); printf("(size = %d)\n", qSize(q)); } Stack s; stackCreate(&s, 128); for (int i = 0; i < 255; ++i) { stackPush(&s, i); } while (!stackEmpty(&s)) { printf("%d ", stackTop(&s)); stackPop(&s); } }
int precedenceParser() { // hlavni funkce precedencni analyzy tStack stack1; stackInit(&stack1); tStack stack2; stackInit(&stack2); tOpData temp; infix2post(&stack1, &stack2); // prevedeni vyrazu na postfixovou notaci while(stackEmpty(&stack2) != true) { // prechozeni na druhy zasobnik + kontrolni vypsani stackPop(&stack2, &temp); stackPush(&stack1, temp); } int x = reduction(&stack1, &stack2); // provedeni redukce printf("Navratovy typ vyrazu: %d\n", x); stackDispose(&stack1); stackDispose(&stack2); return x; }
/* ** Pomocná funkce doOperation. ** Zpracuje operátor, který je pøedán parametrem c po naètení znaku ze ** vstupního pole znakù. ** ** Dle priority pøedaného operátoru a pøípadnì priority operátoru na ** vrcholu zásobníku rozhodneme o dal¹ím postupu. Délka pøevedeného ** výrazu a takté¾ ukazatel na první volné místo, do kterého se má zapisovat, ** pøedstavuje parametr postLen, výstupním polem znakù je opìt postExpr. */ void doOperation ( tStack* s, char c, char* postExpr, unsigned* postLen ) { char tmp; // Opakuj dokym nebude mozne vlozit operator do zasobnika while(1) { // Zasobnik je prazdny, povolene vlozit operator. if(stackEmpty(s)) break; else { stackTop(s, &tmp); // Na vrchole zasobniku je lava zatvorka, povolene // vlozit operator. if(tmp == '(') break; else if(c == '*' || c == '/') { // Na vrchole zasobniku je operator s nizsou prioritou, // povolene vlozit operator. if(tmp == '+' || tmp == '-') break; } } // Na vrchole zasobniku je operator s rovnakou alebo vyssiou // prioritou. Vyjmi ho a uloz do vystupneho vyrazu. postExpr[(*postLen)++] = tmp; stackPop(s); } stackPush(s, c); }
// Starting with a valid triangulation, uses the Edge Flip algorithm to // refine the triangulation into a Constrained Delaunay Triangulation. void tessMeshRefineDelaunay( TESSmesh *mesh, TESSalloc *alloc ) { // At this point, we have a valid, but not optimal, triangulation. // We refine the triangulation using the Edge Flip algorithm // // 1) Find all internal edges // 2) Mark all dual edges // 3) insert all dual edges into a queue TESSface *f; EdgeStack stack; TESShalfEdge *e; int maxFaces = 0, maxIter = 0, iter = 0; stackInit(&stack, alloc); for( f = mesh->fHead.next; f != &mesh->fHead; f = f->next ) { if ( f->inside) { e = f->anEdge; do { e->mark = EdgeIsInternal(e); // Mark internal edges if (e->mark && !e->Sym->mark) stackPush(&stack, e); // Insert into queue e = e->Lnext; } while (e != f->anEdge); maxFaces++; } } // The algorithm should converge on O(n^2), since the predicate is not robust, // we'll save guard against infinite loop. maxIter = maxFaces * maxFaces; // Pop stack until we find a reversed edge // Flip the reversed edge, and insert any of the four opposite edges // which are internal and not already in the stack (!marked) while (!stackEmpty(&stack) && iter < maxIter) { e = stackPop(&stack); e->mark = e->Sym->mark = 0; if (!tesedgeIsLocallyDelaunay(e)) { TESShalfEdge *edges[4]; int i; tessMeshFlipEdge(mesh, e); // for each opposite edge edges[0] = e->Lnext; edges[1] = e->Lprev; edges[2] = e->Sym->Lnext; edges[3] = e->Sym->Lprev; for (i = 0; i < 4; i++) { if (!edges[i]->mark && EdgeIsInternal(edges[i])) { edges[i]->mark = edges[i]->Sym->mark = 1; stackPush(&stack, edges[i]); } } } iter++; } stackDelete(&stack); }
void *stackTop (arraystack_t *stack) { if (stackEmpty (stack)) { return NULL; } return stack->data + stack->top; }
Item pop(){ if(!stackEmpty()){ return stack[top--]; }else{ printf("Stack overflow!\n"); exit(0); } }
/* ================= Stack pop(stack)::= ================= */ element pop() {/*delete and return the top element from the stack*/ if (top==-1) { stackEmpty();/*returns an error key*/ /*****fixing*/ } return stack[top--]; }
/* Zavolá funkci stackEmpty a vytiskne výsledek. */ void use_stack_empty ( tStack* ptrstack ) { solved = 1; int i =stackEmpty( ptrstack ); if ( ! solved ) printf("[W] Funkce stackEmpty nebyla implementována.\n"); else printf("stackEmpty returned '%s'\n", i ? "TRUE" : "FALSE" ); }
StackItem stackTop(void) { assert(!stackEmpty()); StackItem stackItem = { objectStack[stackSize - 1], objectTypeStack[stackSize - 1] }; return stackItem; }
char* infixToPostfix(char const* str) { generic_stack* infixStack = stackAllocate(1); generic_stack* output = stackAllocate(1); char peek; for (; *str; ++str) { stackPeek(infixStack, &peek); if (*str == '(') { peek = '('; stackPush(infixStack, &peek); } else if (*str == ')') { while (peek != '(') { stackPop(infixStack, &peek); stackPush(output, &peek); stackPeek(infixStack, &peek); } //Discard the '(' stackPop(infixStack, &peek); } else { while (!stackEmpty(infixStack) && precidence(peek) >= precidence(*str)) { stackPop(infixStack, &peek); stackPush(output, &peek); //Update the peeked stackPeek(infixStack, &peek); } stackPush(infixStack, str); } } while (!stackEmpty(infixStack)) { stackPop(infixStack, &peek); stackPush(output, &peek); } peek = '\0'; stackPush(output, &peek); char* result = malloc(stackSize(output)); memcpy(result, output->data, output->current); stackFree(infixStack); stackFree(output); return result; }
void infix2post(tStack *stack1, tStack *stack2) { tOpData temp; // token tOpData help; // pomocne do { token tok = gib_tok(); if((zpracuj(tok, &temp)) == 0) { if(temp.element == ID) { stackPush(stack2, temp); //printf("%d\n", temp.element); } else { if(temp.element == LEFT) stackPush(stack1, temp); else { if(temp.element == RIGHT) { stackPop(stack1, &help); while(help.element != LEFT) { stackPush(stack2, help); stackPop(stack1, &help); //printf("%d\n", help.element); } } else { while(stackEmpty(stack1) != true && (priority(temp.element) <= priority(stackTop(stack1).element))) { stackPop(stack1, &help); stackPush(stack2, help); //printf("%d\n", help.element); } stackPush(stack1, temp); } } } } } while(temp.element != DOLAR); /*while(stackEmpty(stack2) != true) { stackPop(stack2, &temp); printf("%d\n", temp.element); }*/ }
// DFS, walk the game-tree: bool tryNextPiece(int depth) { char *word[]={"plain","flip","rot","rotFlip"}; Piece piece; int i,dir=0; #ifdef VERBOSE printf("Try depth(%d)\n",depth); #endif if (stackEmpty()) { // we've won! recurse-out answer printf("Winning!\n"); printf("BoardState:\n"); printPiece(board); printf("--~~~--\nunwinding solution:\n"); return true; } piece = popPiece(); i=tryDir(piece,5,depth); // Horizontal bits if (i>=0) goto weWin; //flip piece dir++; i=tryDir(flip(piece),5,depth); if (i>=0) goto weWin; // rot: dir++; i=tryDir(rot(piece),1,depth); if (i>=0) goto weWin; // rotFlip: dir++; i=tryDir(flipRot(piece),1,depth); if (i>=0) goto weWin; // not sure about this returning pieces bussiness... pushPiece(piece); // but each piece gotta be somewhere // so it makes somekindof sense... return false; weWin: printf("uw [%d]\n",depth); switch (dir){ case 0: printPiece(piece<<(5*i)); break; case 1: printPiece(flip(piece)<<(5*i)); break; case 2: printPiece(rot(piece)<<i); break; case 3: printPiece(flipRot(piece)<<i); break; } printf("Direction: %s, offset: %d\n",word[dir],i); return true; }
void stackDispose(tStack *stack) { tOpData temp; while(stackEmpty(stack) != true) { stackPop(stack, &temp); } stack->top = NULL; }
// 算法6.2 P131 // 采用二叉链表存储结构,visit是对数据元素操作的应用函数 // 中序遍历二叉树T的非递归算法(利用栈),对每个数据元素调用函数visit int inOrderTraverse2(BiTreeLink T,int(*visit)(TElemType)){ SqStack S; BiTreeLink p; initStack(&S); push(&S,T);//根指针进栈 while(!stackEmpty(S)){ while(getTop(S,&p)&&p){ push(&S,p->lchild);//向左走到尽头 } pop(&S,&p);//空指针退栈 if(!stackEmpty(S)){ //访问结点,向右一步 pop(&S,&p); if(!visit(p->data)) return 0; push(&S,p->rchild); } } printf("\n"); return 1; }
/* Starting with a valid triangulation, uses the Edge Flip algorithm to refine the triangulation into a Constrained Delaunay Triangulation. */ int tessMeshRefineDelaunay( TESSmesh *mesh, TESSalloc *alloc ) { /* At this point, we have a valid, but not optimal, triangulation. We refine the triangulation using the Edge Flip algorithm */ /* 1) Find all internal edges 2) Mark all dual edges 3) insert all dual edges into a queue */ TESSface *f; EdgeStack stack; TESShalfEdge *e; TESShalfEdge *edges[4]; stackInit(&stack, alloc); for( f = mesh->fHead.next; f != &mesh->fHead; f = f->next ) { if ( f->inside) { e = f->anEdge; do { e->mark = EdgeIsInternal(e); /* Mark internal edges */ if (e->mark && !e->Sym->mark) stackPush(&stack, e); /* Insert into queue */ e = e->Lnext; } while (e != f->anEdge); } } // Pop stack until we find a reversed edge // Flip the reversed edge, and insert any of the four opposite edges // which are internal and not already in the stack (!marked) while (!stackEmpty(&stack)) { e = stackPop(&stack); e->mark = e->Sym->mark = 0; if (!tesedgeIsLocallyDelaunay(e)) { int i; tessMeshFlipEdge(mesh, e); // for each opposite edge edges[0] = e->Lnext; edges[1] = e->Lprev; edges[2] = e->Sym->Lnext; edges[3] = e->Sym->Lprev; for (i=0;i<3;i++) { if (!edges[i]->mark && EdgeIsInternal(edges[i])) { edges[i]->mark = edges[i]->Sym->mark = 1; stackPush(&stack, edges[i]); } } } } stackDelete(&stack); return 1; }
void *stackPop (arraystack_t *stack) { if (stackEmpty(stack)) { return NULL; } void *element = malloc (sizeof (void*)); memcpy (element, stack->data + stack->top, sizeof (element)); stack->data[stack->top] = NULL; stack->top -= 1; return element; }
int peek (stack stk) { int top; if (stackEmpty(stk)) { stackUnderflow(); return -1; }else { return top; } }
//将二叉搜索树转换为双端列表 struct node *treeToList(struct node *root) { if (NULL == root) { return root; } struct node *current = root, *head = NULL, *prev = NULL; struct stack *s; while (current != NULL) { stackPush(s, current); current = current->small; } while(!stackEmpty(s)) { current = stackPop(s); if (NULL == head) { head = current; } current->small = prev; if (prev != NULL) { prev->large = current; } prev = current; if (current->large != NULL) { current = current->large; while (current != NULL) { stackPush(s, current); current = current->small; } } } if (prev != NULL) { prev->large = NULL; } return head; }
int* preorderTraversal(struct TreeNode* root, int* returnSize) { *returnSize = 0; if(NULL == root){ return NULL; } Stack* stack = (Stack*)malloc(sizeof(Stack)); stackCreate(stack, 16); int* result = (int*)malloc(sizeof(int)*16); struct TreeNode* current = NULL; do{ if(!stackEmpty(stack)){ current = stackTop(stack); stackPop(stack); }else{ current = root; } result[*returnSize] = current->val; *returnSize = *returnSize + 1; if(*returnSize > 16){ result = (int*)realloc(result, sizeof(int)*(*returnSize+16)); } if(current->right){ stackPush(stack, current->right); } if(current->left){ stackPush(stack, current->left); } }while(!stackEmpty(stack)); stackDestroy(stack); free(stack); return result; }
void stackTop ( const tStack* s, char* c ) { /* -------- ** Vrací znak z vrcholu zásobníku prostøednictvím parametru c. ** Tato operace ale prvek z vrcholu zásobníku neodstraòuje. ** Volání operace Top pøi prázdném zásobníku je nekorektní ** a o¹etøete ho voláním funkce stackError(SERR_TOP). ** ** Pro ovìøení, zda je zásobník prázdný, pou¾ijte døíve definovanou ** funkci stackEmpty. */ if (stackEmpty(s)) stackError(SERR_TOP); else *c = s->arr[s->top]; }
/* ** Pomocná funkce untilLeftPar. ** Slou¾í k vyprázdnìní zásobníku a¾ po levou závorku, pøièem¾ levá závorka ** bude také odstranìna. Pokud je zásobník prázdný, provádìní funkce se ukonèí. ** ** Operátory odstraòované ze zásobníku postupnì vkládejte do výstupního pole ** znakù postExpr. Délka pøevedeného výrazu a té¾ ukazatel na první volné ** místo, na které se má zapisovat, pøedstavuje parametr postLen. ** ** Aby se minimalizoval poèet pøístupù ke struktuøe zásobníku, mù¾ete zde ** nadeklarovat a pou¾ívat pomocnou promìnnou typu. */ void untilLeftPar ( tStack* s, char* postExpr, unsigned* postLen ) { char tmp; while(!stackEmpty(s)) { // Vyjmi znak zo zasobnika stackTop(s, &tmp); stackPop(s); // V pripade lavej zatvorky ukonci cyklus if (tmp == '(') break; // Prirad znak do vyrazu a zvecsi dlzku postExpr[(*postLen)++] = tmp; } }
void stackPop ( tStack* s ) { /* -------- ** Odstraní prvek z vrcholu zásobníku. Pro ovìøení, zda je zásobník prázdný, ** pou¾ijte døíve definovanou funkci stackEmpty. ** ** Vyvolání operace Pop pøi prázdném zásobníku je sice podezøelé a mù¾e ** signalizovat chybu v algoritmu, ve kterém je zásobník pou¾it, ale funkci ** pro o¹etøení chyby zde nevolejte (mù¾eme zásobník ponechat prázdný). ** Spí¹e ne¾ volání chyby by se zde hodilo vypsat varování, co¾ v¹ak pro ** jednoduchost nedìláme. ** */ if (!stackEmpty(s)) (s->top)--; }
int pop (stack stk) { int top; if (stackEmpty(stk)) { stackUnderflow(); return -1; } else { top = stk[stk[0]]; stk[0]--; printf("Popped: %c\n", top); return top; } }
void stackTop ( const tStack* s, char* c ) { /* -------- ** Vrací znak z vrcholu zásobníku prostøednictvím parametru c. ** Tato operace ale prvek z vrcholu zásobníku neodstraòuje. ** Volání operace Top pøi prázdném zásobníku je nekorektní ** a o¹etøete ho voláním funkce stackError(SERR_TOP). ** ** Pro ovìøení, zda je zásobník prázdný, pou¾ijte døíve definovanou ** funkci stackEmpty. */ if (stackEmpty(s)==-1) //Pokud je vrchol zasobniku nastaven na -1 (je prazdny) zavolam funkci pro vypis chyby stackError(SERR_TOP); else{ *c=s->arr[s->top]; //do promenne c dal hodnotu z vrcholu zasobniku } }
void DFSNonRecurTraverse(graph *g, void (*visitFunc)(char e)) { visitFunc = print; int v = 0, w = 0; char elem = 0; for(v = 0; v < g->verNum; v++) visited[v] = 0; stack *s = (stack*)malloc(sizeof(stack)); initStack(s); for(v = 0; v < g->verNum; v++) { if(!visited[v]) { push(s, g->vertex[v]); (*visitFunc)(g->vertex[v]); visited[v] = 1; v = firstAdjVex(g, v); } while(!stackEmpty(*s)) { if(!visited[v]) { push(s, g->vertex[v]); visited[v] = 1; (*print)(g->vertex[v]); v = firstAdjVex(g, v); } else { getTop(s, &elem); w = findIndex(*g, elem); v = nextAdjVex(g, w, v); } if(v == -1) { pop(s, &elem); w = findIndex(*g, elem); v = nextAdjVex(g, w, v); } } } destroyStack(s); s->stackSize = 0; free(s); s = NULL; }
void traverse(int k,void (*visit)(int)) { link_t x; int t; stackInit(100); stackPush(k); while(!stackEmpty()){ t=stackPop(); if(visited[t]==0) visit(t); visited[t]=1; Push(adj[t]); } }