static void load_stack(void) { struct stack *stack; struct value *value; int idx; idx = readreg(); if (idx >= 0) { stack = &bmachine.reg[idx]; value = NULL; if (stack_size(stack) > 0) { value = stack_pop(stack); } if (value != NULL) push(value); else warnx("stack register '%c' (0%o) is empty", idx, idx); } }
int main() { srand(time(NULL)); stack_t s; stack_create(&s, sizeof(int)); int i; for(i=0; i<N; i++){ int temp = rand()%N; printf("push: %d\n", temp); stack_push(&s, &temp); } int data; while( (stack_pop(&s, &data) == GERROR_OK) ) printf("pop: %d\n", data); stack_destroy(&s); return 0; }
int main() { int n; Stack* s = stack_create(1); stack_push(s, 42); stack_push(s, 37); stack_pop(s); stack_push(s, 20); stack_push(s, -3); n = stack_size(s); printf("%d\n", n); stack_destroy(s); List_stack* ls = list_stack_create(); list_stack_push(ls, 42); list_stack_push(ls, 37); list_stack_push(ls, -3); list_stack_pop(ls); n = list_stack_size(ls); printf("%d\n", n); list_stack_destroy(ls); }
static void load_stack(void) { int index; struct stack *stack; struct value *value, copy; index = readreg(); if (index >= 0) { stack = &bmachine.reg[index]; value = NULL; if (stack_size(stack) > 0) { value = stack_pop(stack); } if (value != NULL) push(stack_dup_value(value, ©)); else warnx("stack register '%c' (0%o) is empty", index, index); } }
/** * Remove an item. Remove also all its children if the parameter * 'iSingle' is 1. */ void radix_tree_item_destroy(_radix_tree_item_t ** ptree_item, FRadixTreeDestroy fDestroy, int iSingle) { gds_stack_t * stack= stack_create(32); _radix_tree_item_t * tree_item= *ptree_item; while (tree_item != NULL) { /* If all children are to be removed, push them onto stack. */ if (!iSingle) { if (tree_item->left != NULL) stack_push(stack, tree_item->left); if (tree_item->right != NULL) stack_push(stack, tree_item->right); } /* Destroy the item. */ if ((tree_item->data != NULL) && (fDestroy != NULL)) { fDestroy(&tree_item->data); tree_item->data= NULL; } /* If the current item is empty (no child) or if we delete all child, then free the item's memory. */ if (((tree_item->left == NULL) && (tree_item->right == NULL)) || !iSingle) { FREE(tree_item); *ptree_item= NULL; } /* Any other child to be removed ? */ if (stack_depth(stack) > 0) tree_item= (_radix_tree_item_t *) stack_pop(stack); else tree_item= NULL; } stack_destroy(&stack); }
/** * media_entity_graph_walk_next - Get the next entity in the graph * @graph: Media graph structure * * Perform a depth-first traversal of the given media entities graph. * * The graph structure must have been previously initialized with a call to * media_entity_graph_walk_start(). * * Return the next entity in the graph or NULL if the whole graph have been * traversed. */ struct media_entity * media_entity_graph_walk_next(struct media_entity_graph *graph) { if (stack_top(graph) == NULL) return NULL; /* * Depth first search. Push entity to stack and continue from * top of the stack until no more entities on the level can be * found. */ while (link_top(graph) < stack_top(graph)->num_links) { struct media_entity *entity = stack_top(graph); struct media_link *link = &entity->links[link_top(graph)]; struct media_entity *next; /* The link is not enabled so we do not follow. */ if (!(link->flags & MEDIA_LNK_FL_ENABLED)) { link_top(graph)++; continue; } /* Get the entity in the other end of the link . */ next = media_entity_other(entity, link); if (WARN_ON(next->id >= MEDIA_ENTITY_ENUM_MAX_ID)) return NULL; /* Has the entity already been visited? */ if (__test_and_set_bit(next->id, graph->entities)) { link_top(graph)++; continue; } /* Push the new entity to stack and start over. */ link_top(graph)++; stack_push(graph, next); } return stack_pop(graph); }
/* returns 0 on no cycle, -1 on cycle */ int graph_dfs(struct graph *graph, int root, struct stack *topost) { graph->vertices[root].color = GRAY; struct vertex *curv, *next; struct stack *st = stack_new(sizeof(struct vertex *)); int ret = 0; int pos; curv = graph->vertices + root; stack_push(st, &curv); while (!stack_empty(st)) { stack_peek(st, &curv); if (curv->dfs_idx >= curv->nr) { curv->color = BLACK; pos = vindex_lookup(graph, curv->data); stack_push(topost, &pos); stack_pop(st, &curv); continue; } next = vertex_get_next_edge(graph, curv); if (next->color == GRAY) { ret = -1; if (graph_debug_resolve) { const char *visiting_pkg = curv->data; const char *visited_pkg = next->data; fprintf(stderr, "Cyclic dep with %s -> ... -> %s -> %s\n", visited_pkg, visiting_pkg, visited_pkg); } break; } else if (next->color == WHITE) { next->color = GRAY; stack_push(st, &next); } } stack_free(st); return ret; }
/* * Parse the input stream and return an action stack. * See Wikipedia again. */ static obj_t *parse(instream_t *in) { AUTO_ROOT(actions, NIL); AUTO_ROOT(yylval, NIL); AUTO_ROOT(tmp, make_fixnum(TOK_EOF)); AUTO_ROOT(stack, NIL); stack_push(&stack, tmp); tmp = make_fixnum(sym_index(start_symbol)); stack_push(&stack, tmp); int tok = yylex(&yylval, in); while (true) { int sym = fixnum_value(stack_pop(&stack)); assert(0 <= sym && sym < symbols_size); uint_fast8_t rule = get_rule(symbols[sym], tok); if (rule != NO_RULE) { const production_t *pp = &grammar[rule]; int j; for (j = strlen(pp->p_rhs); --j >= 0; ) { tmp = make_fixnum(sym_index(pp->p_rhs[j])); stack_push(&stack, tmp); } if (pp->p_action) stack_push(&actions, *pp->p_action); } else { if (sym == TOK_EOF) break; /* XXX raise an exception here. */ assert(sym == tok && "syntax error"); if (!is_null(yylval)) stack_push(&actions, yylval); if (!stack_is_empty(actions) && fixnum_value(stack_top(stack)) == TOK_EOF) break; yylval = NIL; tok = yylex(&yylval, in); } } POP_FUNCTION_ROOTS(); return actions; }
void * average() { /* Récupération des variables pour la condition de fin */ pthread_mutex_lock(&files); pthread_mutex_lock(&newfract); pthread_mutex_lock(&finished); int flag = flagFiles; int nread = readFract; int nfinished = finishedFract; pthread_mutex_unlock(&files); pthread_mutex_unlock(&newfract); pthread_mutex_unlock(&finished); struct fractal *bestAv = fractal_new("empty", 1, 1, 0.0, 0.0); //Variable où stocker la meilleure fractale while (!flag || nread != nfinished) { //Tant qu'il y a des fichiers à lire ou que le nombre de fractales créées est différent du nombre de fracales terminées sem_wait(&full2); //On attend qu'il y ait quelque chose dans le buffer pthread_mutex_lock(&mutex2); //On lock struct fractal *test = stack_pop(&buffer2); //On prend la fractale; if (fractal_get_av(test) > fractal_get_av(bestAv)) { //Si la fractale est meilleure que celle précédement en mémoire fractal_free(bestAv); bestAv = test; } else { fractal_free(test); } pthread_mutex_unlock(&mutex2); sem_post(&empty2); /* Update des variables pour la condition de fin */ pthread_mutex_lock(&files); pthread_mutex_lock(&newfract); pthread_mutex_lock(&finished); finishedFract++; //Une fracatle supplémentaire est terminée flag = flagFiles; nread = readFract; nfinished = finishedFract; pthread_mutex_unlock(&files); pthread_mutex_unlock(&newfract); pthread_mutex_unlock(&finished); } pthread_exit((void *) bestAv); //Renvoie la meilleure fractale }
int main(int argc, char **argv) { int val; my_stack_t int_stack; stack_init(&int_stack, sizeof(int)); for(val = 0; val < 6; val++) { stack_push(&int_stack, &val); } while (!is_stack_empty(&int_stack)) { stack_pop(&int_stack, &val); printf("This just popped: %d\n", val); } stack_destroy(&int_stack); return 0; }
int dec2base(int num, int base) { EntryType digit; // 用于接收出栈操作返回的元素值 StackPtr ps; stack_init(ps); // 构造空栈 // 执行辗转相除操作,将余数入栈 while ( num){ stack_push(ps, num%base); num = num / base; } // 按由高位到低位的顺序输出八进制数 while ( !stack_empty(ps) ){ stack_pop(ps, &digit); printf(" %d", digit); } stack_destroy(ps); return 0; }
int main() { char *data = NULL; t_stack *stack = stack_init(); printf("Initial stack size: %d\n", stack->count); // Push data in stack_push(stack, "test"); stack_push(stack, "a"); stack_push(stack, "is"); stack_push(stack, "this"); printf("Full stack size: %d\n", stack->count); // Show all of the data while(stack->head != NULL) { stack_pop(stack, (void**) &data); printf("%s\n", data); } // Double check it is empty printf("Empty stack size: %d\n", stack->count); free(stack); return 0; }
// ascii to integer struct variable *sys_atoi(struct context *context) { struct variable *value = (struct variable*)stack_pop(context->operand_stack); char *str = (char*)((struct variable*)array_get(value->list.ordered, 1))->str->data; uint32_t offset = value->list.ordered->length > 2 ? ((struct variable*)array_get(value->list.ordered, 2))->integer : 0; int n=0, i=0; bool negative = false; if (str[offset] == '-') { negative = true; i++; }; while (isdigit(str[offset+i])) n = n*10 + str[offset + i++] - '0'; n *= negative ? -1 : 1; variable_push(context, variable_new_int(context, n)); variable_push(context, variable_new_int(context, i)); return variable_new_src(context, 2); }
static void assert_convert_ldc_string(enum vm_type expected_type, long long expected_value) { unsigned char code[] = { OPC_LDC, 0xff }; uint32_t cp_infos[NR_CP_ENTRIES]; uint8_t cp_types[NR_CP_ENTRIES]; struct expression *expr; struct basic_block *bb; const_set_int32_t(cp_infos, 0xff, 0x00); cp_types[0xff] = CAFEBABE_CONSTANT_TAG_STRING; bb = alloc_simple_bb(code, ARRAY_SIZE(code)); convert_ir_const(bb->b_parent, cp_infos, NR_CP_ENTRIES, cp_types); expr = stack_pop(bb->mimic_stack); assert_value_expr(expected_type, expected_value, &expr->node); assert_true(stack_is_empty(bb->mimic_stack)); expr_put(expr); free_simple_bb(bb); }
int process_rotate_general(Stack s, int n, PROCESSOR_RESULT result) { double theta, x, y; StackItem *cur; if (stack_size(s) < 2 * n + 1) { return throw_error("Impossivel realizar operação. Motivo: há menos elementos na pilha do que o necessário (stack underflow).\n", result); } theta = stack_pop(s); cur = s->next; for (int i = 0; i < n; i++) { y = cur->value; x = cur->next->value; cur->value = (x * sin(theta) + y * cos(theta)); // calculate new y cur->next->value = (x * cos(theta) - y * sin(theta)); // calculate new x cur = cur->next->next; } return PROCESSOR_SUCCESS; }
/* CORPO DELLE FUNZIONI */ int main(int argc, char *argv[]) { stack_t *input; item_t *comand; user_t *user = NULL; /* se non esiste la cartella base, la creiamo */ if(path_exist(BASE) < 0){ if(create_directory(BASE, 0777) < 0){ perror("create_directory"); exit(EXIT_FAILURE); } } /* leggiamo l'input da linea comando */ input = read_input(argv, argc); if(input == NULL){ perror("read_input"); exit(EXIT_FAILURE); } /* ordiniamo le richieste */ stack_sort(input); /* eseguimo tutte le richieste */ while(input ->len > 0){ /* estraiamo l'azione corrente */ comand = stack_pop(input); if(comand == NULL){ perror("stack_pop"); exit(EXIT_FAILURE); } /* eseguiamo il comando */ if(execute_comand(comand ->value, comand ->arg, &user) < 0){ perror("execute_program"); exit(EXIT_FAILURE); } } /* usciamo dal programma */ exit(EXIT_SUCCESS); }
int main(void) { STACK *handle = NULL; int i, n, ret; int *val = NULL; handle = stack_create(sizeof(int), MAX); ERRP(NULL == handle, goto ERR1, 1, "create failed!\n"); for (i = 0; i < MAX; i++) { n = rand() % 100; printf("%d ", n); ret = stack_push(handle, &n); ERRP(ret == -1, goto ERR2, 1, "push failed!\n"); } printf("\n"); stack_travel(handle, op); printf("\n"); for (i = 0; i < MAX; i++) { val = stack_pop(handle); if (val != NULL) printf("%d ", *val); else printf("-1 "); } printf("\n"); stack_destroy(&handle); return 0; ERR2: stack_destroy(&handle); ERR1: return -1; }
int equality_expression(struct token *token) { if ((token->op_type == EQUALS) || (token->op_type == NOTEQUALS)){ tree_mknode(EQUALITY_EXPRESSION); //initialize new identifier and set op_type to same as token struct identifier *eq = malloc(sizeof(struct identifier)); type_op(eq->type); eq->op_type = token->op_type; eq->lexeme = token->lexeme; tree_add_attr(eq, 3); input_consume(); stack_pop(); free(token); return 0; } else{ log_error(EQUALITY_EXPRESSION); return -1; } }
/****************************************************************************** **函数名称: xml_parse_end **功 能: 处理结束节点(处理</XXX>格式的结束) **输入参数: ** stack: XML栈 ** parse: 解析文件缓存信息 **输出参数: **返 回: 0: 成功 !0: 失败 **实现描述: **注意事项: XML大小写敏感 **作 者: # Qifeng.zou # 2013.02.05 # ******************************************************************************/ static int xml_parse_end(xml_tree_t *xml, Stack_t *stack, xml_parse_t *parse) { size_t len; xml_node_t *top; const char *ptr; parse->ptr += XML_MARK_END2_LEN; /* 跳过</ */ ptr = parse->ptr; /* 1. 确定结束节点名长度 */ while (XmlIsMarkChar(*ptr)) { ++ptr; } if (!XmlIsRPBrackChar(*ptr)) { log_error(xml->log, "XML format is wrong![%-.32s]", parse->ptr); return XML_ERR_FORMAT; } len = ptr - parse->ptr; /* 2. 获取栈中顶节点信息 */ top = (xml_node_t*)stack_pop(stack); if (NULL == top) { log_error(xml->log, "Get stack top member failed!"); return XML_ERR_STACK; } /* 3. 节点名是否一致 */ if (len != top->name.len || (0 != strncmp(top->name.str, parse->ptr, len))) { log_error(xml->log, "Mark name is not match![%s][%-.32s]", top->name.str, parse->ptr); return XML_ERR_MARK_MISMATCH; } ptr++; parse->ptr = ptr; return XML_OK; }
static void quick_sort_with_stack(int arr[], int left, int right) { struct stack* s = stack_new(); stack_push(s, left, right); while (! stack_empty(s)) { int l; int r; stack_pop(s, &l, &r); if (l < r) { int m = lomuto_partition(arr, l, r); stack_push(s, l, m-1); stack_push(s, m+1, r); } } stack_del(s); }
int main(void){ stack_fkvm_t stack; if (stack_init(&stack) == -1){ return 1; } for (int i=0; i<200; i++){ if (stack_push(&stack,i) == -1){ return 1; } } while (!is_empty(&stack)){ printf("%lu ",stack_pop(&stack)); } printf("\n"); stack_destroy(&stack); return 0; }
struct variable *sys_disconnect(struct context *context) { struct variable *arguments = (struct variable*)stack_pop(context->operand_stack); if (arguments->list->length < 2) { struct variable *sockets = (struct variable *)array_get(arguments->list, 1); assert_message(sockets->type == VAR_LST, "non list of sockets"); for (int i=0; i<sockets->list->length; i++) { struct thread_argument *tc = (struct thread_argument *)array_get(sockets->list, i); close(tc->fd); CyaSSL_free(tc->ssl); } } else { const int32_t fd = param_int(arguments, 1); close(fd); map_remove(socket_listeners, (void*)(VOID_INT)fd); } return NULL; }
extern node_t * ct_node_at(node_t *root, int index) { node_t *node = root; int counter = 0; int go_down = 1; node_stack_t *stack; if (index < 0) return NULL; stack = stack_init(32); for(;;) { if ((LEFT_NODE(node) != NULL) && go_down) { stack_push(stack, node); node = LEFT_NODE(node); } else { if (counter == index) { stack_delete(stack); return node; } counter++; if (RIGHT_NODE(node) != NULL) { node = RIGHT_NODE(node); go_down = 1; } else { if (stack_is_empty(stack)) { stack_delete(stack); return NULL; } node = stack_pop(stack); go_down = 0; } } } }
/* * Print Binary Search Tree in in-order fashion without using recursion using single stack. * * @cur_root : Pointer to the root of the binary search tree. */ void bst_print_inorder_nonrecur_1stack(node_t *cur_root) { /* Stack of nodes of which we have processed left sub-tree. */ Stack_t nodes_stack; node_t *current = cur_root; bool done = 0; stack_init(&nodes_stack); while (!done) { /* Reach the left most tNode of the current tNode */ if(current != NULL) { /* place pointer to a tree node on the stack before traversing the node's left subtree */ stack_push(&nodes_stack, current); current = current->left; } /* backtrack from the empty subtree and visit the tNode at the top of the stack; however, if the stack is empty, you are done */ else { if (!stack_empty(&nodes_stack)) { current = stack_pop(&nodes_stack); printf("%d ", current->data); /* we have visited the node and its left subtree. Now, it's right subtree's turn */ current = current->right; } else done = 1; } } }
include <stdio.h> #include "include/my_stack.h" int main(void) { int x; while ( ! stack_is_full() ) { scanf("%d", &x); stack_push(x); } while ( !stack_is_empty() ) { x = stack_pop(); printf("%d\t", x); } printf("\n"); return 0; }
int cast_expression(struct token *token) { printf("hello from cast_expression\n");//DEBUG //need to get 'type' ')' 'lrvalue' struct hashentry *ifkw = hash_retrieve(kwtable, token->lexeme); if (ifkw == NULL){ //not a keyword, error log_error(CAST_EXPRESSION); return -1; } else { //TODO implement actual check tree_mknode(CAST_EXPRESSION); tree_add_attr(ifkw->data, 0); input_consume(); stack_pop(); free_token(token); stack_push(LRVALUE); stack_push(TOKEN_CLOSEPAREN); return 0; } }
// return 0 if interaction should continue; else stack error. int interact(struct stack *stack) { int value; char op; int retval; printf("> "); do { op = getc(stdin); } while (isspace(op)); switch (op) { case '+': retval = plus(stack); break; case '-': retval = minus(stack); break; case 'e': retval = EXIT_OP; break; case 'p': retval = stack_pop(stack, &value); if (retval != 0) break; printf("%d\n", value); break; default: ungetc(op, stdin); if (scanf("%d", &value) == 1) { retval = stack_push(stack, value); } else { retval = INVALID_CHAR; } } return retval; }
void print_topo_order(struct graph *graph, struct stack *topost) { int idx; int cnt = 0; const char *curpkg; while (!stack_empty(topost)) { stack_pop(topost, &idx); curpkg = graph_get_vertex_data(graph, idx); if (!curpkg) { continue; } if (cnt++ > 0) { printf(" -> %s", curpkg); } else { printf("%s", curpkg); } } printf("\n"); }
void test_empty (stack_t stack) { /* Test Size */ if (stack_size (stack) != 0) { printf ("Empty Stack: Size Failed\n"); exit (EXIT_FAILURE); } /* Test peek and pop functions */ if (stack_pop (stack) != NULL) { printf ("Empty Stack: Pop Failure\n"); exit (EXIT_FAILURE); } if (stack_peek (stack) != NULL) { printf ("Empty Stack: Peek Failure\n"); exit (EXIT_FAILURE); } }
// the gpio class void native_stm32_gpio_invoke(u08_t mref){ if(mref == NATIVE_METHOD_SETINPUT) { u08_t bit = stack_pop(); u08_t port = stack_pop(); DEBUGF("native setinput %bd/%bd\n", port, bit); // *ddrs[port] &= ~_BV(bit); } else if(mref == NATIVE_METHOD_SETOUTPUT) { u08_t bit = stack_pop(); u08_t port = stack_pop(); DEBUGF("native setoutput %bd/%bd\n", port, bit); // *ddrs[port] |= _BV(bit); } else if(mref == NATIVE_METHOD_SETBIT) { u08_t bit = stack_pop(); u08_t port = stack_pop(); DEBUGF("native setbit %bd/%bd\n", port, bit); GPIO_SetBits((GPIO_TypeDef *)(GPIOA_BASE + port*0x00000400), (uint16_t)(bit<<1)); } else if(mref == NATIVE_METHOD_CLRBIT) { u08_t bit = stack_pop(); u08_t port = stack_pop(); DEBUGF("native clrbit %bd/%bd\n", port, bit); GPIO_ResetBits((GPIO_TypeDef *)(GPIOA_BASE + port*0x00000400), (uint16_t)(bit<<1)); } else error(ERROR_NATIVE_UNKNOWN_METHOD); }