int main() { char str[100]; int i; Stack *operands = newStack(); // Allocate a new stack Stack *operators = newStack(); // Allocate a new stack scanf("%s", str); for(i = 0; str[i]; i++) { if(isOperand(str[i])) push(operands, &str[i]); else if(isOperator(str[i])) { while(!isEmpty(operators) && *(char *)peek(operators) != '(' && hasLessPriority(str[i], *(char *)peek(operators))) push(operands, &*(char *)pop(operators)); if(str[i] == ')') { while(!isEmpty(operators) && *(char *)peek(operators) != '(') push(operands, &*(char *)pop(operators)); if(!isEmpty(operators)) pop(operators); // Pop the opening bracket '(' but not store anywhere. } if(str[i] != ')') push(operators, &str[i]); } } while(!isEmpty(operators)) push(operands, &*(char *)pop(operators)); /* while(!isEmpty(operands)) printf("%c ", *(char *)pop(operands)); printf("\n\n"); */ char s[100]; int j=0; while(!isEmpty(operands)) { s[j++] = *(char *)pop(operands); // if(s[j-1] == '(') // j--; } s[j] = '\0'; for(i=j-1; i>=0; i--) printf("%c", s[i]); return 0; }
// -------------------------------------------------- Construct new evaluator object Eval newEval( const char* expr ) { Eval ev = safe_malloc( sizeof *ev ); ev->instream = expr; ev->Ators = newStack(); ev->Ands = newStack(); ev->numbin = 0; return ev; }
PRIMITIVE curlyOpen(/* Token closeAction */ uWord level){ // The stack contains the Token of closeAction too but it isn't used. if(level==execution.l){ paren++; stack().drop(); newStack(0); }else if(level<execution.l) stack().push2(level,curlyOpenT); else{ stack().push2(execution.l,paren.l); execution=level;counter=0;paren=1; newStack(0); } }
/** main **/ int main() { int ndx; mystack_t *stack1; mystack_t *stack2; startThreadSystem(); /* Create stack1 */ stack1 = newStack(100); /* And exercise it by spawning 4 threads */ for (ndx=0; ndx<4; ndx++) { parm[ndx].myID = ndx; parm[ndx].numWords = 30000; parm[ndx].stack = stack1; if ((ndx%2) == 0) { id[ndx] = newThread(pusher); } else { id[ndx] = newThread(popper); } } /* Create stack2 */ stack2 = newStack(5000); /* And exercise it by spawning 6 threads */ for (; ndx<10; ndx++) { parm[ndx].myID = ndx; parm[ndx].numWords = 9000; parm[ndx].stack = stack2; if ((ndx%2) == 0) { id[ndx] = newThread(pusher); } else { id[ndx] = newThread(popper); } } /* Wait for everyone to end */ for (ndx=0; ndx<10; ndx++) { twait(id[ndx]); if ((ndx % 2) == 1) { printf("Popper %d count = %d\n", ndx, parm[ndx].popcount); } } printf("Main thread done\n"); exit(0); }
//------------------------------------------------------------ //clear or destroy int clear( bvs_ptr tree ) { ptr_IStackA stack = newStack( sizeof(node_ptr) ); //zasobnik ukazatelov if ( stack == NULL ) return TREE_ERROR; node_ptr curr_node = tree->root; // korenovy ukazatel node_ptr ptr; //pomocny ukazatel uzla while ( (curr_node != NULL) || (SEmpty(stack) != 1) ) { if (curr_node == NULL){ curr_node = *((node_ptr * )Stop(stack)); Spop(stack); } else { if (curr_node->right != NULL) //ulozenie praveeho podstromu Spush(stack, &(curr_node->right)); ptr = curr_node; curr_node=curr_node->left; destroyNode(ptr); free(ptr); } } destroyStack(stack); free(stack); return TREE_OK; }
Stack* newStack() { #ifdef SPC_USE_MALLOC_CACHE unsigned int i,j; ENTRY; for(i=0;i<stackBucketSize;++i) { if(stackBucketMask[i]!=0xff) {//look for which one isnt used for(j=1;j<256;j=j<<1) if(!stackBucketMask[i]&j) { //got it stackBucketMask[i]|=j; //set bucket flag return(stackBucket+(i*sizeof(char)+j)*sizeof(Stack)); } } } //blast, didn't find it =( expandCache(); return newStack(); #else Stack*s; ENTRY s=(Stack*)malloc(sizeof(Stack)); s->stack=0; //no data s->depth=0; //no data return(s); #endif }
/** * @brief * @param S * @param X * * */ void StackPush(Stack S, ElementType X) { PtrToStackNode temp = newStack(); temp->element = X; temp->next = S->next; S->next = temp; }
float caculate(char *postfix) { int i,j; float result; Stack s; char c; newStack(&s); for (i = 0; i < strlen(postfix); i++) { c = postfix[i]; if (!isOperator(c)) push(&s,c - 48); else { float second = pop(&s); float first = pop(&s); switch(c) { case '+': result = first + second;break; case '-': result = first - second;break; case '*': result = first * second;break; case '/': result = first / second;break; case '^': result = 1; for(j = 0; j < second; j++) result *= first; break; } push(&s,result); } } return pop(&s); }
int main(int argc, char *argv[]) { int buf[5]; Stack stack = newStack(buf); int i, val; srand((unsigned)time(NULL)); printf("push:"); for (i = 0; i < rand()%10 + 1; i++) { val = rand()%10 + 1; if (push(&stack, val)) { printf("%d ", val); } else { printf("E "); } } printf("\n"); printf("pop:"); for (i = 0; i < rand()%10 + 1; i++) { if (pop(&stack, &val) == true) { printf("%d ", val); } else { printf("E ", val); } } printf("\n"); return EXIT_SUCCESS; }
void assert_stack_is_not_empty_when_an_element_is_pushed() { Stack *stk = newStack(10); push(stk, 5); assert(FALSE == isStackEmpty(stk)); freeStack(stk); }
void assert_pop_will_return_last_element_pushed() { Stack *stk = newStack(10); push(stk, 18); assert(18 == pop(stk)); freeStack(stk); }
int main(int argc, char **argv) { int N = (argc < 2) ? 20 : atoi(argv[1]); if (N < 20) N = 20; Stack s = newStack(); int i; char x[50]; for (i = 0; i < N; i++) { if (random()%10 > 5) { if (!emptyStack(s)) { char *str = popFrom(s); printf("Remove %s\n",str); free(str); } } else { randomString(x); pushOnto(s,x); printf("Insert %s\n",x); } showStack(s); } disposeStack(s); return 0; }
void test_intStack(){ struct stack intStack; int x, n; int i=0; int *buf; newStack(&intStack, sizeof(int), NULL, NULL); printf("Enter the number of elements: "); scanf("%d",&n); while(n--){ scanf("%d",&x); /* While pushing, we are sending the address of the variable x. This is because if we are to send the value of x directly, then the prototype of the function which does the push should be Push(struct stack *s, int item) in the case we are pushing ints. If we are pusing char then the prototype should change to char item. So to avoid this, we are passing the address of x so that it can be received as void* */ Push(&intStack, &x); } // Display stack buf = (int*)display(&intStack); while(buf[i]){ printf("%d ",buf[i]); i++; } free(buf); }
int isPathDfs(Graph g, Vertex v, Vertex w) { int isPath = FALSE; Stack s = newStack(); // create a new stack Vertex currentVertex = 0; int *visited = calloc(g->nV, sizeof(int)); // allocate + init to 0 int i = 0; assert(visited != NULL); push(s, v); // push first vertex onto stack visited[v] = TRUE; // mark it as visited while ( !isEmptyStack(s) ){ // still have vertices to traverse currentVertex = pop(s); // get a vertex from the stack printf("Visiting: %d\n", currentVertex); visited[currentVertex] = TRUE; // mark it as visited if (currentVertex == w) { isPath = TRUE; } for (i = 0; i < g->nV; i++){ // search for a vertex we haven't visited if (g->edges[currentVertex][i] && !visited[i]){ // ignore pendants push(s, i); // push vertex onto stack visited[i] = TRUE; } } } free(visited); deleteStack(s); return isPath; }
LongInt::LongInt() { StackAr <int> newStack(1000001); Queue <int> newQueue(1000001); intStack = newStack; intQueue = newQueue; }
void assert_stack_is_empty_after_all_elements_are_popped() { Stack *stk = newStack(10); push(stk, 9); pop(stk); assert(TRUE == isStackEmpty(stk)); freeStack(stk); }
void assert_pop_will_return_last_element_pushed_with_multiple_elements() { Stack *stk = newStack(10); push(stk, 16); push(stk, 21); assert(21 == pop(stk)); freeStack(stk); }
void symtabInit() { currentLevel = 0; indexOfNextEntry = 0; indexOfNextBlock = 0; blockIndices[indexOfNextBlock++] = 0; addressStack = newStack(); push(addressStack, 0); }
/** * Inspired from UNIX fork(). * This is what happens : * thisThread->programcounter=pc; // current pc * thisThread->stack=new StackFrame(36); // so on thisThread stack, top stack element is an integer 0 * push the integer 1 // in contrast: on current stack, top stack element is integer 1 * In other words: return 0 if it's the new child Thread else 1 */ void native_java_lang_Thread_fork_I() { native_java_lang_Thread* thisThread=(native_java_lang_Thread*) top.s1.a; thisThread->stack= (stackFrame4Debug_t*) newStack(HAIKU_InitialOtherThreadStackSize); thisThread->programcounter=pc; thisThread->stackframe= (jstack) &thisThread->stack->stack[0]; thisThread->stackpointer= (jstack) &thisThread->stack->stack[1]; // stack[0] is not allowed because areturn() will trigger a (this time wrong) dequeue top.s1.i=1; }
int main() { Stack *stack = newStack(); Queue *queue = newQueue(); StackElement popped; QueueElement eq; //int test /* enqueue(queue, 4); enqueue(queue, 5); enqueue(queue, 6); enqueue(queue, 7); enqueue(queue, 8); push(stack, 4); push(stack, 5); push(stack, 6); push(stack, 7); push(stack, 8); StackElement popped; while( (popped = pop(stack)) != -1) { printf("%d\n",popped); } */ //char test push(stack, 'a'); push(stack, 'b'); push(stack, 'c'); push(stack, 'd'); push(stack, 'f'); enqueue(queue, 'a'); enqueue(queue, 'b'); enqueue(queue, 'c'); enqueue(queue, 'd'); enqueue(queue, 'f'); printf("Stack:\n"); while( (popped = pop(stack)) != -1) { printf("%c\n",popped); } printf("Queue:\n"); while( (eq = dequeue(queue)) != -1) { printf("%c\n",eq); } freeStack(stack); freeQueue(queue); return 1; }
main() { Stack s1,s2,s3; int c,x,y; int result = 0,memo = 0; char choice; newStack(&s1); newStack(&s2); newStack(&s3); printf("\n\tChuong trinh cong 2 so nguyen duong lon\n"); printf("\nNhap so thu nhat: "); while((c = getchar())!= '\n') push(&s1,c-48); printf("Nhap so thu hai: "); while((c = getchar())!='\n') push(&s2,c-48); while(!empty(s1) || !empty(s2)) { x = (empty(s1)) ? 0 : pop(&s1); y = (empty(s2)) ? 0 : pop(&s2); result = x + y + memo; push(&s3,result % 10); memo = result / 10; } if(memo != 0) push(&s3,memo); printf("Ket qua la: "); while(!empty(s3)) printf("%d",pop(&s3)); printf("\n"); printf("\nBan co muon tiep tuc[y/n]?.."); scanf("%s",&choice); if(choice == 'y' || choice == 'Y') { getchar(); main(); } return 0; }
void test_stringStack(){ struct stack stringStack; int i=0; char *friends[] = {"Alis", "Bob", "Michael"}; char *temp; newStack(&stringStack, sizeof(char*), stringFree, stringDisplay); for(i=0; i<3; i++){ char *copy = strdup((const char*)friends[i]); /* Reason why we should pass © and not just copy: If we pass just copy, then the memcpy in the push function will write into s->elems array, the value pointed to by the string. x /10wx s->elems 0x602060: 0x73696c41 0x00000000 0x00000000 0x00000000 0x602070: 0x00000000 0x00000000 0x00000000 0x00000000 If you see, the 1st element should ideally contain the pointer to the string "Alis". Instead it has stored the value(string) in the stack. Our stack now contains Alis in its 1st element. The free function will now try to free 0x73696c41 which is an invalid address. Thus we should pass © and the elems will look like (gdb) p item // item is the pointer to char* of Alis. $2 = (void *) 0x7fffffffdfe8 (gdb) x /10wx s->elems 0x602060: 0x00602440 0x00000000 0x00000000 0x00000000 0x602070: 0x00000000 0x00000000 0x00000000 0x00000000 i.e 0x7fffffffdfe8 points to 0x00602440 which points to "Alis" the memcpy will store the value at 0x7fffffffdfe8 to the 1st element in the stack which is 0x00602440 */ Push(&stringStack, ©); } stackDisplay(&stringStack); disposeStack(&stringStack); /* Here again we should pass the address of the character pointer temp. If we just pass the value of temp, then the memcpy in the POP function, will try to write the value in the stack to the value pointer to by this array. Currently, temp is not pointing to anything and it is not the duty of the stack to fill in the value. It is just going to return the address of the value in the stack in this variable. */ for(i=0; i<4; i++){ if(Pop(&stringStack, &temp)){ printf("\nString is %s\n",temp); free(temp); } else{ printf("\nStack is Empty\n"); return; } } }
static Stack newProperty(Property prop) { Stack s = newStack(); s->type = 'p'; s->data.prop = prop; return s; }
static Stack newString(char *string) { Stack s = newStack(); s->type = 's'; s->data.string = string; return s; }
char* test_stack_pop() { mu_assert("stack pop with NULL-pointer should return NULL", stackPop(NULL)==NULL); stack* s = newStack(); mu_assert("empty stack pop should return NULL", stackPop(s)==NULL); free(s); return 0; }
void findPath(int length, int index, int cost, int start) { Stack s; int mode; int current; int j = 0; int buffer; int *array; array = malloc(length*sizeof(int)); assert(array != NULL); s = newStack(length); while(index > 0) { mode = index%6; push(mode,&s); index = index/6; if (mode ==0) { index--; } } buffer = s.top; while((s.top) >= 0) { array[j] = pop(&s); j++; } printf("%d ", start); current = start; for (j=0; j < buffer; j++) { switch (array[j]) { case 1: current += 1; printf("(+1) -> %d ", current); break; case 2: current *= 2; printf("(*2) -> %d ", current); break; case 3: current *= 3; printf("(*3) -> %d ", current); break; case 4: current -= 1; printf("(-1) -> %d ", current); break; case 5: current /= 2; printf("(/2) -> %d ", current); break; case 6: current /= 3; printf("(/3) -> %d ", current); break; } } printf("\nlength: %d, cost: %d\n", length, cost); }
/***************************** evaluatePostfix ******************************** void evaluatePostfix(Out out, Customer customerM[], int iNumCustomer, QueryResult resultM[]) Purpose: This function takes in a query in postfix form and evaluate it to return an array of booleans representing each customer that the query returns. Parameters: I Out out The query in postfix format. I Customer customerM[] The array of customer for which the query will be evaluated. I int iNumCustomer The number of customers in customerM[]. O QuerryResult resultM[] The array of QuerryResult (booleans) representing which customer satisfy the conditions of the query. Notes: The function will call a warning function to return an empty resultM[] and print a warning message if an query is invalid. Return value: resultM[] parm - An array of QueryResult, each boolean represent the customer of the same index in customerM[]. *******************************************************************************/ void evaluatePostfix(Out out, Customer customerM[], int iNumCustomer, QueryResult resultM[]) { Stack stack = newStack(); Customer currentCustomer; Element operand1, operand2, evalElem, postElem; int i, j, iPopResult; for (i = 0; i < iNumCustomer; i++) //for each customer { currentCustomer = customerM[i]; //the current customer for (j = 0; j < out->iOutCount; j++) //for each token in the postfix query { postElem = out->outM[j]; //the current token switch (postElem.iCategory) { case CAT_OPERAND: //if token is an operand, just push push(stack, postElem); break; case CAT_OPERATOR: iPopResult = popTwoOperands(stack, &operand1, &operand2); //pop 2 operands and store them in operand1 and operand2 switch (iPopResult) { case 0: //call operator handling function evalElem = operatorHandling(&operand1, &operand2, &postElem, ¤tCustomer); push(stack, evalElem); //push current result to stack break; case WARN_NOT_ENOUGH_OPER: warningExit(WARN_NOT_ENOUGH_OPER, resultM, stack); return; //stop evaluating this query } break; } } //there should only be one element in the stack when the evaluation is over //we pop that element and send in to the result array at the index of the current customer resultM[i] = (pop(stack)).bInclude; if(isEmpty(stack) == FALSE) { warningExit(WARN_TOO_MANY_OPER, resultM, stack); return; //stop evaluating this query } } freeStack(stack); }
void startSemantics(FILE* file, DynamicTable* symbols) { strcpy(identifier, ""); strcpy(label, ""); strcpy(procedure, ""); strcpy(type, ""); strcpy(destination, ""); strcpy(operator, ""); strcpy(auxiliar, ""); constant = -1; ifCount = -1; whileCount = -1; params = 0; newFreeList(); newStack(&ifs); newStack(&whiles); fprintf(file, "_start\tSC\tmain\n\tHM\t_start\n\n"); addToTable(symbols, "main", "main", "procedure"); }
/* mark nodal domain containing grid[i][j] as counted non-recursive version inputs: grid - 2d array of function values counted - 2d array indicating whether a point has been counted i - row of initial point in grid j - column of initial point in grid nd - number of current nodal domain ny - rows in grid nx - columns in grid precondition: grid and counted are ny x nx outputs: return value: area of domain (in pixels) updates stats */ int findDomain(bit_array_t *signs, bit_array_t *counted, int i, int j, int nd, int ny, int nx) { stack *s = newStack(); push(s, j, i); bit_array_set(counted, j, i); int x, y; int currentSign; int size = 0; while (pop(s, &x, &y)) { size++; currentSign = bit_array_get(signs, j, i); #ifdef DEBUG domain_numbers[y][x] = nd; #endif // orthongal directions // left if (x >= 1 && !bit_array_get(counted, x-1, y)) { if (bit_array_get(signs, x-1, y) == currentSign) { bit_array_set(counted, x-1, y); push(s, x - 1, y); } } // above if (y >= 1 && !bit_array_get(counted, x, y-1)) { if (bit_array_get(signs, x, y-1) == currentSign) { bit_array_set(counted, x, y-1); push(s, x, y-1); } } // right if (x < nx-1 && !bit_array_get(counted, x+1, y)) { if (bit_array_get(signs, x+1, y) == currentSign) { bit_array_set(counted, x+1, y); push(s, x+1, y); } } // below if (y < ny-1 && !bit_array_get(counted, x, y+1)) { if (bit_array_get(signs, x, y+1) == currentSign) { bit_array_set(counted, x, y+1); push(s, x, y+1); } } } destroyStack(s); return size; }
void constructChildValues(ESA *esa) { int n = esa->n+1; stack *s = newStack(); push(s, 0); // TODO: Make sure that this correctly reaches the end. for (int i=1; i<n; i++) { while (esa->LCP[i] < esa->LCP[ peek(s) ]) pop(s); if (esa->LCP[i] == esa->LCP[ peek(s) ]) esa->accross[pop(s)] = i; push(s, i); } /** Construct Up/Down values. ***************/ // Reset the stack. emptyStack(s); int lastIndex = -1; push(s, 0); for (int i=1; i<n; i++) { while (esa->LCP[i] < esa->LCP[ peek(s) ] ) { lastIndex = pop(s); int top = peek(s); if ( esa->LCP[i] <= esa->LCP[top] && esa->LCP[top] != esa->LCP[lastIndex] ) esa->down[top] = lastIndex; if (lastIndex != -1) { esa->up[i] = lastIndex; lastIndex = -1; } } push(s, i); } freeStack(s); }