void printStack(stack* s){ if(emptyStack(s) == 1){ printf("\nThe stack is empty.\n"); return; } stack* tempS = createStack(); dnode* tempN = frontStack(s); data* d = createData(tempN->d->i1,tempN->d->i2,tempN->d->f1); while(emptyStack(s) != 1){ tempN = frontStack(s); printData(tempN->d); d = createData(tempN->d->i1,tempN->d->i2,tempN->d->f1); pushStack(tempS,d); popStack(s); } while(emptyStack(tempS) != 1){ tempN = frontStack(tempS); d = createData(tempN->d->i1,tempN->d->i2,tempN->d->f1); pushStack(s,d); popStack(tempS); } return; }
void pushPair(VM* vm) { Object* obj = newObject(vm, ObjPair); obj->head = popStack(vm); obj->tail = popStack(vm); pushStack(vm, obj); }
int main(int argc, char const *argv[]) { initStack(); //Set stack pointers int i; for (i = 0; i < MAX_STACK_SIZE; i++) //Fill stack from 0 to 4 pushStack(i); int *popValue = popStack(); //Set pop value (first one in, last one out) (Again, it's 4 because we use ints, otherwise, we'd use index values) while(popValue != NULL) //Starting at newest value, pop value out to screen { printf("%d\n", *popValue); popValue = popStack(); } return 0; }
char* simplifyPath(char* path) { int len = strlen(path); if (!path || len < 2) return path; Stack stack; if (*(path + len - 1) == '/') { len--; *(path + len) = '\0'; } char *str = (char *)malloc(sizeof(char)* (len + 1)); initStack(&stack, len); int status; while (status = getElem(&path, str)) { if (status == 1) { pushStack(&stack, str); } else if(status == 2){ popStack(&stack); } } if (stack.top == 0) { stack.elem[0] = '/'; stack.top = 1; stack.pos[stack.top] = 1; } stack.elem[stack.pos[stack.top]] = '\0'; return stack.elem; }
// ----------------------------------------------------------- Free evaluator object void freeEval( Eval ev ) { while (!isemptyStack( ev->Ators )) { freeOperator( topStack( ev->Ators ) ); popStack( ev->Ators ); } freeStack( ev->Ators ); while (!isemptyStack( ev->Ands )) { freeOperand( topStack( ev->Ands ) ); popStack( ev->Ands ); } freeStack( ev->Ands ); free( ev ); }
/* pops out all the elements from the stack */ void destroyStack(Stack stk) { while(stk) { stk = popStack(stk); } }
int main (int argc, char *argv[]) { int i = 0; Stack *myStack = createStack(); Node *n = NULL; if (myStack == NULL) { printf("main: Cannot create stack. Exiting!\n"); return 0; } for (i = 0; i < 10; i++) { n = createNode(i); pushStack(myStack, n); } printStack(myStack); for (i = 0; i < 11; i++) { n = popStack(myStack); if (n == NULL) { printf("main: popped NULL!\n"); printStack(myStack); break; } printf("main: popped %d\n", n->data); free(n); n = NULL; printStack(myStack); } return 0; }
int main(void){ int i, x; char array[] = {'(','(','a','+','b',')','+','(','(', 'c','+','d',')',')',')'}; size_t tam = sizeof(array) / sizeof(array[0]); tStack stack; creatStack(&stack); for(i=0; i<tam; i++){ if(array[i] == '('){ x = pushStack(&stack, array[i]); } if((array[i] == ')') && (i>0)){ x = popStack(&stack); } } if(stack.size == 0){ printf("\nAccepted\n"); } else{ printf("\nRejected\n"); } printStack(&stack); system("pause"); return 0; }
//=================================================================== // Function to undo a delete of a company. Does not allow to undo // delete of a company that is already in the BST //=================================================================== void undoDelete(DATA_HEAD *data) { COMPANY* companyNode; int isDuplicate; //If there is something in the stack if(!emptyStack(data->pStack)) { companyNode = (COMPANY*)popStack(data->pStack); //Check to see if there is duplicate isDuplicate = searchHash(data, companyNode->companyName, companyNode); //If there is, print and error, else, insert into the hashed array if(isDuplicate == 1) { printf("ERROR: DUPLICATE DATA\n"); printf("%s has already been entered into the system\n", companyNode->companyName); free(companyNode); } else { printf("%s reinserted into the system\n", companyNode->companyName); insertManager(data, companyNode); updateCollision(data); (data->count)++; printf("\nNumber Of Data Records: %d\n", data->count); } } else printf("Nothing to undo.\n"); //nothing in the stack printf("\n"); }
void LuaState::foreachKey(std::function<void(std::string, LuaState&)> fun) { pushStack(); while (lua_next(_L, -2) != 0) { fun(pullStack<std::string>(-2), *this); popStack(); } }
Oop* __fastcall Interpreter::primitivePerform(CompiledMethod& , unsigned argCount) { SymbolOTE* performSelector = m_oopMessageSelector; // Save in case we need to restore SymbolOTE* selectorToPerform = reinterpret_cast<SymbolOTE*>(stackValue(argCount-1)); if (ObjectMemoryIsIntegerObject(selectorToPerform)) return primitiveFailure(1); m_oopMessageSelector = selectorToPerform; Oop newReceiver = stackValue(argCount); // lookupMethodInClass returns the Oop of the new CompiledMethod // if the selector is found, or Pointers.DoesNotUnderstand if the class // does not understand the selector. We succeed if either the argument // count of the returned method matches that passed to this primitive, // or if the selector is not understood, because by this time the // detection of the 'does not understand' will have triggered // the create of a Message object (see createActualMessage) into // which all the arguments will have been moved, and which then replaces // those arguments on the Smalltalk context stack. i.e. the primitive // will succeed if the message is not understood, but will result in // the execution of doesNotUnderstand: rather than the selector we've // been asked to perform. This works because // after a doesNotUnderstand detection, the stack has a Message at stack // top, the selector is still there, and argCount is now 1. Consequently // the Message gets shuffled over the selector, and doesNotUnderstand is // sent MethodOTE* methodPointer = findNewMethodInClass(ObjectMemory::fetchClassOf(newReceiver), (argCount-1)); CompiledMethod* method = methodPointer->m_location; if (method->m_header.argumentCount == (argCount-1) || m_oopMessageSelector == Pointers.DoesNotUnderstandSelector) { // Shuffle arguments down over the selector (use argumentCount of // method found which may not equal argCount) const unsigned methodArgCount = method->m_header.argumentCount; // #pragma message("primitivePerform: Instead of shuffling args down 1, why not just deduct 1 from calling frames suspended SP after exec?") Oop* const sp = m_registers.m_stackPointer - methodArgCount; // We don't need to count down the overwritten oop anymore, since we don't ref. count stack ops // Not worth overhead of calling memmove here since argumentCount // normally small for (unsigned i=0;i<methodArgCount;i++) sp[i] = sp[i+1]; popStack(); executeNewMethod(methodPointer, methodArgCount); return primitiveSuccess(0); } else { // The argument count did not match, so drop out into the Smalltalk // having restored the selector ASSERT(m_oopMessageSelector!=Pointers.DoesNotUnderstandSelector); m_oopMessageSelector = performSelector; return primitiveFailure(0); } }
//clean stack memory void cleanStack(struct stack *s) { while(!isEmptyStack(s)) { popStack(s); } free(s->stk); free(s); }
void LuaState::foreachIndex(std::function<void(int, LuaState&)> fun) { pushStack(); while (lua_next(_L, -2) != 0) { fun(pullStack<int>(-2), *this); popStack(); } }
/* transforms the values string in a binary tree */ void createTree(char *values, int size) { for (int i=0; i<size; i++) { NodeT *aux = createNode(*(values+i)); if (isalpha(aux->value) || (aux->value=='#')) { pushStack(aux); } else if (strchr("+-*/", aux->value)) { NodeT *node = createNode(aux->value); node->right = popStack(); node->left = popStack(); pushStack(node); } } }
bool isSameTree(TreeNode* p, TreeNode* q) { Stack stack_sp, stack_sq, *stack_p = &stack_sp, *stack_q = &stack_sq; initStack(stack_p); initStack(stack_q); while ((p || stack_p->top) && (q || stack_q)) { if (p && q) { pushStack(stack_p, p); pushStack(stack_q, q); p = p->left; q = q->left; } else if (!p && !q) { p = popStack(stack_p); q = popStack(stack_q); if (p->val != q->val) return false; p = p->right; q = q->right; } else return false; } return (p == q) && (stack_p->top == stack_q->top); }
void AbstractXULParser::endElement(const Poco::XML::XMLString & uri, const Poco::XML::XMLString & localName, const Poco::XML::XMLString & qname) { if (mIgnores > 0) { mIgnores--; return; } popStack(); }
JSValue Function::callFromC(JSValue* argsBegin, JSValue* argsEnd) { JSValue r; auto vm = JSVM::instance(); auto frame = vm->topFrame(); JSValue *ret = vm->pushStack(argsBegin, argsEnd); callFromVM(ret, ret + (argsEnd - argsBegin)); execute(frame); r = *ret; vm->popStack(int(argsEnd - argsBegin)); return r; }
//print stack. You have to print from the stack. You can not call a print function from dlinklist void printStack(struct stack *s) { // struct data* tDta = NULL; struct stack *tS = createStack(); while(!isEmptyStack(s)) { struct data* tDta = top(s); printData(tDta); pushStack(tS,createData(tDta->v1,tDta->v2)); popStack(s); } while(!isEmptyStack(tS)) { struct data* tDta = top(tS); pushStack(s,createData(tDta->v1,tDta->v2)); popStack(tS); } cleanStack(tS); }
int main() { int i; SqStack *s; s = initStack(); for(i = 0 ; i < 20 ; i++){ int elem = rand()%100; printf("%d\t", elem); // StackElemType temp = {elem, NULL}; pushStack(s, elem); } printf("\n"); printStack(s); StackElemType pPopNode; popStack(s, &pPopNode); printf("%d\n", pPopNode); popStack(s, &pPopNode); printf("%d\n", pPopNode); freeStack(s); }
int main(int argc, char *argv[]) { int i=0; top=NULL; printf(" \n1. Push to stack"); printf(" \n2. Pop from Stack"); printf(" \n3. Display data of Stack"); printf(" \n4. Exit\n"); while(1) { printf(" \nChoose Option: "); scanf("%d",&i); switch(i) { case 1: { int value; printf("\nEnter a value to push into Stack: "); scanf("%d",&value); push(value); display(); break; } case 2: { popStack(); display(); break; } case 3: { display(); break; } case 4: { struct Node *temp; while(top!=NULL) { temp = top->next; free(top); top=temp; } exit(0); } default: { printf("\nwrong choice for operation"); } } } }
// ------------------------------------------------------------ Evaluate one operator. void dispatchEval( Eval ev ) { double result; Operand rightp = topStack( ev->Ands ); popStack( ev->Ands ); Operand leftp = topStack( ev->Ands ); popStack( ev->Ands ); double right = value( rightp ); freeOperand( rightp ); double left = value( leftp ); freeOperand( leftp ); Operator op = topStack( ev->Ators); popStack( ev->Ators ); ev->numbin--; printf( " Evaluating: %g%c%g\n", left, symbolOperator( op ), right ); switch ( symbolOperator( op ) ) { case '+': result = left + right; break; case '-': result = left - right; break; case '*': result = left * right; break; case '/': result = left / right; break; case '%': result = fmod(left, right); break; case '^': result = pow (left, right); break; default: result = HUGE_VAL; /* shouldn't occur */ } freeOperator( op ); Operand And = newOperand( result ); pushStack( ev->Ands, And ); }
void parallel_mandelbrot(struct mandelbrot_thread *args, struct mandelbrot_param *parameters) { #if LOADBALANCE == 1 // Use a stack if(args -> id == 0) { initStack(); } pthread_barrier_wait(&thread_para_barrier); int i; int RowsPerThread = ROWS_PER_TASK; float threadsInv = (float)ROWS_PER_TASK / (float)mandelbrot_param.height; float irange = mandelbrot_param.upper_i - mandelbrot_param.lower_i; int tasksPerThread = (mandelbrot_param.height / ROWS_PER_TASK) / NB_THREADS; for(i = tasksPerThread * args -> id; i < tasksPerThread * (args -> id + 1); i ++) { struct mandelbrot_param tempParam = mandelbrot_param; tempParam.height = ROWS_PER_TASK; tempParam.lower_i = irange * threadsInv * (float)i + mandelbrot_param.lower_i; tempParam.upper_i = irange * threadsInv * (float)(i + 1) + mandelbrot_param.lower_i; pushStack(&tempParam, ROWS_PER_TASK * i); } #endif #if LOADBALANCE == 0 int RowsPerThread = parameters -> height / NB_THREADS; float range = (float)RowsPerThread / (float)parameters -> height; float threadsInv = 1.0f / (float)NB_THREADS; float irange = parameters -> upper_i - parameters -> lower_i; struct mandelbrot_param tempParam = *parameters; tempParam.height = parameters -> height / NB_THREADS; tempParam.lower_i = irange * threadsInv * (float)args -> id + parameters -> lower_i; tempParam.upper_i = irange * threadsInv * (float)(args -> id + 1) + parameters -> lower_i; compute_chunk(&tempParam, RowsPerThread * args -> id, 0); #endif #if LOADBALANCE == 1 while (1) { struct mandelbrot_param_offset* theParamOffset = popStack(); if(theParamOffset == NULL) break; compute_chunk(&(theParamOffset -> theParam), theParamOffset -> heightOffset, 0); } #endif }
int main(void) { int i = 0; struct Node *temp = NULL; top = NULL; puts("1. Push to Stack"); puts("2. Pop from Stack"); puts("3. Display data of Stack"); puts("4. Exit\n"); while(1) { printf("Choose Option : "); scanf_s("%d", &i); switch(i) { case 1: { int value; printf("Enter a number to push into Stack : "); scanf_s("%d", &value); push(value); display(); break; } case 2: { popStack(); display(); break; } case 3: { display(); break; } case 4: { while(top != NULL) { temp = top->next; free(top); top = temp; } exit(0); } } } }
int recover_delayExec( msParam_t *actionCall, msParam_t *delayCondition, ruleExecInfo_t *rei ) { int i; ruleExecDelInp_t ruleExecDelInp; RE_TEST_MACRO( " Calling recover_delayExec" ); i = popStack( &delayStack, ruleExecDelInp.ruleExecId ); if ( i < 0 ) { return( i ); } i = rsRuleExecDel( rei->rsComm, &ruleExecDelInp ); return( i ); }
/***** int _remoteExec(char *inActionCall, char *recoveryActionCall, char *delayCondition, char *hostName, ruleExecInfo_t *rei) { char *args[MAX_NUM_OF_ARGS_IN_ACTION]; int i, argc; ruleExecSubmitInp_t *ruleSubmitInfo; char action[MAX_ACTION_SIZE]; char tmpStr[NAME_LEN]; bytesBuf_t *packedReiAndArgBBuf = NULL; char *ruleExecId; char *actionCall; RE_TEST_MACRO (" Calling _delayExec"); actionCall = inActionCall; if (strstr(actionCall,"##") == NULL && !strcmp(recoveryActionCall,"nop")) { i = parseAction(actionCall,action,args, &argc); if (i != 0) return i; mapExternalFuncToInternalProc(action); argc = 0; } else { actionCall = malloc(strlen(inActionCall) + strlen(recoveryActionCall) + 3); sprintf(actionCall,"%s|%s",inActionCall,recoveryActionCall); args[0] = NULL; args[1] = NULL; argc = 0; } i = packReiAndArg (rei, args, argc, &packedReiAndArgBBuf); if (i < 0) { if (actionCall != inActionCall) free (actionCall); return i; } ruleSubmitInfo = mallocAndZero(sizeof(ruleExecSubmitInp_t)); i = fillSubmitConditions (actionCall, delayCondition, packedReiAndArgBBuf, ruleSubmitInfo, rei); strncpy(ruleSubmitInfo->exeAddress,hostName,NAME_LEN); if (actionCall != inActionCall) free (actionCall); if (i < 0) { free(ruleSubmitInfo); return i; } i = rsRemoteRuleExecSubmit(rei->rsComm, ruleSubmitInfo, &ruleExecId); if (packedReiAndArgBBuf != NULL) { clearBBuf (packedReiAndArgBBuf); free (packedReiAndArgBBuf); } free(ruleSubmitInfo); if (i < 0) return i; free (ruleExecId); snprintf(tmpStr,NAME_LEN, "%d",i); i = pushStack(&delayStack,tmpStr); return i; } ******/ int recover_remoteExec( msParam_t*, msParam_t*, char*, ruleExecInfo_t *rei ) { int i; ruleExecDelInp_t ruleExecDelInp; RE_TEST_MACRO( " Calling recover_delayExec" ); i = popStack( &delayStack, ruleExecDelInp.ruleExecId ); if ( i < 0 ) { return i; } /*** i = rsRemoteRuleExecDel(rei->rsComm, &ruleExecDelInp); ***/ return i; }
//=================================================================== // Writes to output file and calls function to clear out the stack //=================================================================== void saveToFile(DATA_HEAD *data) { COMPANY *temp; FILE *outputFile; char filename[MAX_CHARS]; int i, len; char ch; do { printf("Please enter a filename for output file [enter for default]:"); fgets(filename, MAX_CHARS, stdin); if (filename[0] == '\n') strcpy(filename, "out.txt"); else { //flush new line len = strlen(filename); if (filename[len - 1] == '\n' || filename[len - 1] == '\r') filename[len - 1] = '\0'; // change '\n' to '\0' else while ((ch = getchar()) != '\n' && ch != '\r'); } outputFile = fopen(filename, "w"); } while (!outputFile); //Writes to output file in hashed sequence printf("Writing to %s...\n", filename); for (i = 0; i < data->arraySize; i++) { if (data->pHash[i].status == 1) //status is filled, data exists at index fprintf(outputFile, "%s,%d,%d,%d\n", data->pHash[i].hashData->companyName, data->pHash[i].hashData->revenuePerBillion, data->pHash[i].hashData->profitPerMillion, data->pHash[i].hashData->numberOfEmployees); } //need to free the company name as well as the company //modifying stack ADT does not work since this is specific to this program while (!emptyStack(data->pStack)) { temp = (COMPANY *)popStack(data->pStack); //pop everything from the stack free(temp->companyName); //free company name and then company free(temp); } data->pStack->count = 0; //reset stack data->pStack->top = NULL; fclose(outputFile); printf("\n"); }
void codeGenFuncCall(astNode* root, symTab* symtab, char* id) { astNode* child = root->leftMostChild; short argNb = 0; pushStack(1, symtab); // Word reserved on the stack for return value while(child->rightSibling != NULL) { if(child->rightSibling->type == EXPR) { // Evaluate expressions of each parameter and push them onto the stack computeExpression(child->rightSibling, symtab); argNb++; } child = child->rightSibling; } fprintf(yyoutasm, "\tjal %s\t\t# Jump to function %s and return address is next instruction\n", id, id); // Inconditional jump to callee function fprintf(yyoutasm, "\tnop\n"); popStack(argNb, symtab); // Remove arguments. Top of the stack is now returned value }
BOOL __fastcall Interpreter::primitiveHookWindowCreate() { Oop argPointer = stackTop(); OTE* underConstruction = m_oteUnderConstruction; OTE* receiverPointer = reinterpret_cast<OTE*>(stackValue(1)); if (!underConstruction->isNil() && underConstruction != receiverPointer) { // Hooked by another window - fail the primitive return primitiveFailureWith(1, underConstruction); } if (argPointer == Oop(Pointers.True)) { // Hooking if (underConstruction != receiverPointer) { ASSERT(underConstruction->isNil()); m_oteUnderConstruction= receiverPointer; receiverPointer->countUp(); } } else { if (argPointer == Oop(Pointers.False)) { // Unhooking if (underConstruction == receiverPointer) { tracelock lock(TRACESTREAM); TRACESTREAM << "WARNING: Unhooking create for " << hex << underConstruction << " before HCBT_CREATEWND" << endl; ObjectMemory::nilOutPointer(m_oteUnderConstruction); } else ASSERT(underConstruction->isNil()); } else return primitiveFailureWith(0, argPointer); // Invalid argument } popStack(); return TRUE; }
void fillAreaWithNumber(Point point, int number){ stackIndex = -1; pushStack(point); while(stackIndex >= 0){ point = popStack(); map[point.x][point.y] = 0; sea[point.x][point.y] = number; if(visited[point.x][point.y]) continue; visited[point.x][point.y] = 1; int i; for(i = 0; i < 8; i++){ Point next = nextPoint(point, i); if(isValidPoint(next) && map[next.x][next.y] < 0){ pushStack(next); } } } }
int main() { StackT stack1; StackT *stackPtr1 = &stack1; initStack(stackPtr1); printf("Pushing 'A' 'B' 'C' 'D' onto stack1\n"); pushStack(stackPtr1, 'A'); pushStack(stackPtr1, 'B'); pushStack(stackPtr1, 'C'); pushStack(stackPtr1, 'D'); printf("Popping and displaying all items from stack 1.\n"); while(!isEmptyStack(stackPtr1)) printf("%c ", popStack(stackPtr1)); printf("\n\n"); return 0; }