Пример #1
0
int main()
{
  Stack* stack = stack_new();
  stack_push(stack, 1);
  stack_push(stack, 2);
  stack_push(stack, 3);
  stack_push(stack, 4);

  printf("SIZE: %i\n", stack_size(stack));

  while (!stack_empty(stack))
  {
    printf("%i\n", stack_top(stack));
    stack_pop(stack);
  }

  stack_delete(stack);
}
Пример #2
0
/******************************************************************************
 **函数名称: _xml_node_len
 **功    能: 计算节点打印成XML格式字串时的长度(注: XML有层次结构)
 **输入参数:
 **     root: XML树根节点
 **     stack: 栈
 **输出参数:
 **返    回: 节点及其属性、孩子节点的总长度
 **实现描述: 
 **注意事项: 
 **作    者: # Qifeng.zou # 2013.06.10 #
 ******************************************************************************/
int _xml_node_len(xml_tree_t *xml, xml_node_t *root, Stack_t *stack)
{
    int depth, len;
    xml_node_t *node = root;

    depth = stack_depth(stack);
    if (0 != depth) {
        log_error(xml->log, "Stack depth must empty. depth:[%d]", depth);
        return XML_ERR_STACK;
    }

    len = 0;

    do {
        /* 1. 将要处理的节点压栈 */
        node->temp = node->child;
        if (stack_push(stack, node)) {
            log_error(xml->log, "Stack push failed!");
            return XML_ERR_STACK;
        }
        
        /* 2. 打印节点名 */
        depth = stack_depth(stack);
        
        xml_node_name_len(node, depth, len);
        
        /* 3. 打印属性节点 */
        if (xml_has_attr(node)) {
            xml_node_attr_len(node, len);
        }
        
        /* 4. 打印节点值 */
        xml_node_value_len(node, len);
        
        /* 5. 选择下一个处理的节点: 从父亲节点、兄弟节点、孩子节点中 */
        node = xml_node_next_len(xml, stack, node, &len);
        
    }while (NULL != node);

    if (!stack_empty(stack)) {
        return XML_ERR_STACK;
    }
    return len;
}
Пример #3
0
/**********************************************************************
* FUNCTION NAME:
*   stack_elem_in
*
* DESCRIPTION:
*   This function judge whether the stack has the given element.
*
* INTERFACE:
*   GLOBAL DATA:
*     None
*
*   INPUT:
*      g_stack --stack pointer
*      nd -- judge element
*   OUTPUT:
*     None
*
*   INPUT/OUTPUT:
*    None
*
* AUTHOR:
*   Fu Pei
*
* RETURN VALUE:
* 
* return 1 if the stack has the element else return 0
*
* NOTES:
*
*********************************************************************/
int stack_elem_in(stack_t* g_stack,node_t* nd)
{
	int ret = 0;
	/*stack  isn't empty*/
    if (!stack_empty(g_stack))
	{
		int i = 0;
		/*find element in stack*/
		for ( ; i <= g_stack->top ; i++)
		{
			if ((*(g_stack->head))[i] == nd)
			{
				ret = PROCESS_SUCCESS;
				break;
			}
		}
	}
	return ret;
}
Пример #4
0
void tree_traverse_s3(tree *btree)
{
    tree *pre = NULL;
    stack_push(btree);
    while(!stack_empty()){
        btree = stack_top();
        if((btree->left == NULL && btree->right == NULL) ||
              (pre != NULL &&(pre == btree->left || pre == btree->right))){
            printf("%d ", btree->data);
            stack_pop();
            pre = btree;
        }else{
            if(btree->right != NULL)
                stack_push(btree->right);
            if(btree->left != NULL)
                stack_push(btree->left);
        }
    }
}
Пример #5
0
pthread_t * thread_pool_get_free(thread_pool *pool)
{
    pthread_t *free_thread_place;
    assert(pool != NULL);
    fprintf(stderr, "Thread pool get free.\n");
    if(!stack_empty(pool->unused)) {
        //fprintf(stderr, "Thread pool get free, stack not empty.\n");
        free_thread_place = pool->threads + stack_top(pool->unused);
        //fprintf(stderr, "Thread pool get free, stack: ");
        //stack_printf(pool->unused);
        pool->unused = stack_pop(pool->unused);
        pool->running_threads ++;
        //fprintf(stderr, "\n");
        //stack_printf(pool->unused);
        //fprintf(stderr, "\n");
        return free_thread_place;
    }
    return NULL;
}
Пример #6
0
void avl_destroy(sb_avl * instance)
{
	// Do an inorder traversal, adding node pointers onto a stack. After the
	// traversal, empty the stack while freeing nodes. Once all nodes are
	// freed, free the stack and free the AVL instance. This ensures that
	// freeing nodes before traversal is complete would not cause the
	// traversal to fail.
	avl_node * node;
	sb_stack * s = stack_init();
	avl_inorder(instance->root, avl_destroy_callback, (void *) s);
	while (!stack_empty(s)) {
		node = (avl_node *) stack_top(s);
		free(node);
		stack_pop(s);
	}
	stack_destroy(s);
	free(instance);
	return;
}
Пример #7
0
/******************************************************************************
 **函数名称: xml_node_free
 **功    能: 释放指定节点,及其所有属性节点、子节点的内存
 **输入参数:
 **     xml: 
 **     node: 被释放的节点
 **输出参数:
 **返    回: 0: 成功 !0: 失败
 **实现描述: 
 **     1. 将孩子从链表中剔除
 **     2. 释放孩子节点及其所有子节点
 **注意事项: 除释放指定节点的内存外,还必须释放该节点所有子孙节点的内存
 **作    者: # Qifeng.zou # 2013.02.27 #
 ******************************************************************************/
int xml_node_free(xml_tree_t *xml, xml_node_t *node)
{
    Stack_t _stack, *stack = &_stack;
    xml_node_t *curr = node, *parent = node->parent, *child;

    /* 1. 将此节点从孩子链表剔除 */
    if ((NULL != parent) && (NULL != curr)) {
        if (xml_delete_child(xml, parent, node)) {
            return XML_ERR;
        }
    }

    if (stack_init(stack, XML_MAX_DEPTH)) {
        log_error(xml->log, "Init stack failed!");
        return XML_ERR_STACK;
    }

    do {
        /* 1. 节点入栈 */
        curr->temp = curr->child;
        if (stack_push(stack, curr)) {
            stack_destroy(stack);
            log_error(xml->log, "Push stack failed!");
            return XML_ERR_STACK;
        }

        /* 2. 释放属性节点: 让孩子指针指向真正的孩子节点 */
        xml_attr_free(xml, curr, child);

        /* 3. 选择下一个处理的节点: 从父亲节点、兄弟节点、孩子节点中 */
        curr = xml_free_next(xml, stack, curr); 
    } while(NULL != curr);

    if (!stack_empty(stack)) {
        stack_destroy(stack);
        log_error(xml->log, "Stack is not empty!");
        return XML_ERR_STACK;
    }

    stack_destroy(stack);
    return XML_OK;
}
Пример #8
0
int main(){
  stack_init();
  printf("%d\n", stack_count());
  stack_push(5);
  stack_push(2);
  stack_push(10);
  printf("%d\n", stack_count());
 
  stack_dup();
  stack_add();
  printf("%d\n", stack_count());
  int x;
  puts("");
  while(!stack_empty()){
    x = stack_pop();
    printf("%d\n", x);
  }
  
  return 0;
}
Пример #9
0
/**
 * @brief Pops an object from a stack.
 * 
 * @details Pops the top object from the stack pointed to by @p s.
 * 
 * @param s Stack where the object should be popped from.
 * 
 * @returns The object on the top of the stack.
 */
object_t stack_pop(struct stack *s)
{
	object_t obj;       /* Object in top node. */
	struct snode *node; /* Top node.           */
	
	/* Sanity check. */
	assert(s != NULL);
	assert(!stack_empty(s));
	
	/* Unlink node. */
	node = s->head.next;
	s->head.next = node->next;
	s->size--;
	
	/* Get object. */
	obj = node->obj;
	stack_node_destroy(node);
	
	return (obj);
}
Пример #10
0
/**
 * Solves the exrecise
 *
 * Exercise 10 from the 4th workbook
 * 
 * @param seq Sequence pointer
 * @param stack Stack pointer
 * @return void
 */
static void solve_exercise(seq_ptr *seq, stack_ptr *stack)
{
  char c; int aux = 0;
  if( ! seq_end(seq)) c = seq_read_first(seq);

  while( ! seq_end(seq) && ! stack_full(stack)) {
    if( ! isdigit(c)) {
      stack_push(stack, c);
    } else {
      aux = atoi(&c);
      while(aux > 0 && ! stack_empty(stack)) {
        stack_pop(stack);
        aux--;
      }
    }
    c = seq_read_next(seq);
  }

  seq_close(seq);
}
static int __init print_processes_backwards(void)
{
    LIST_HEAD(data_stack);
    int result = 0; // OK

    stack_entry_t *task_entry = NULL;
    struct task_struct *task = NULL;
    char *task_name = NULL;

    for_each_process (task) {
        task_name = kmalloc(TASK_COMM_LEN, GFP_KERNEL);

        if (task_name) {
            task_entry = create_stack_entry(task_name);
            if (task_entry) {
                task_name = get_task_comm(task_name, task);
                stack_push(&data_stack, task_entry);
            } else {
                kfree(task_name);
                result = -ENOMEM;
                break;
            }
        } else {
            result = -ENOMEM;
            break;
        }
    }

    while (!stack_empty(&data_stack)) {
        task_entry = stack_pop(&data_stack);
        task_name = STACK_ENTRY_DATA(task_entry, char*);
        delete_stack_entry(task_entry);

        if (result != -ENOMEM) {
            printk(KERN_ALERT "task name = %s\n", task_name);
        }
        kfree(task_name);
    }

    return result;
}
Пример #12
0
int main(int argc,char** argv)
{
	int i,m,a,b;
	long long k;
	char_stack* s;
	char* ans;

	while(scanf("%d",&m)!=EOF)
	{
		if(m==0)
		{
			break;
		}
		scanf("%d%d",&a,&b);
		k=a+b;
		s=stack_malloc();
		if(k)
		{
			while(k)
			{
				stack_push(s,(k%m)+'0');
				k/=m;
			}
		}
		else/* k=0应该直接放一个0*/
		{
			stack_push(s,'0');
		}
		ans=(char*)malloc((s->top+2)*sizeof(char));
		i=0;
		while(!stack_empty(s))
		{
			ans[i++]=stack_pop(s);
		}
		ans[i]=0;
		printf("%s\n",ans);
		stack_free(s);
		free(ans);
	}
	return 0;
}
Пример #13
0
void execute(struct byte_array *program, find_c_var *find)
{
#ifdef DEBUG
    display_program(program);
#endif

    DEBUGPRINT("execute:\n");
    null_check(program);
    program = byte_array_copy(program);
    byte_array_reset(program);

    struct context *context = context_new(false);
    context->find = find;
#ifdef DEBUG
    context->indent = 1;
#endif
    if (!setjmp(trying))
        run(context, program, NULL, false);

    assert_message(stack_empty(context->operand_stack), "operand stack not empty");
}
Пример #14
0
struct identifier_s *context_lookup(const char *key) {
	struct symbol_table_s *table; 
	struct identifier_s *result;
	assert(!stack_empty(&stack));
	table = (struct symbol_table_s *) stack_top(&stack);

	while (table) {
		result = identifier_lookup(table, key);
		if (result)
			return result;

		/* assert(table->definition); */
		if (table->definition)
			table = ((struct identifier_s *) table->definition)->
				parent;
		else /* TODO: */
			return context_c_lookup(key);
	}

	return 0;
}
int main(void){
    int i;
    stack_t* s;
    pessoa p;
    stack_initialize(&s,constructor_pessoa,destructor_pessoa);
    for(i=0;i<5;i++){
        printf("Cadastrando pessoa %d\n",i+1);
        cadastra_pessoa(&p);
        stack_push(s,&p);
    }
    while(!stack_empty(s)){
        printf("\n**Imprimindo pessoa**\n");
        p =  *(pessoa*) stack_top(s);
        stack_pop(s);
        imprime_pessoa(&p);

        printf("\n");
    }
    stack_delete(&s);
    return 0;
}
Пример #16
0
static void _do_bst_traverse_inorder_iterative_(TreeNode *root, Visitor visitor)
{
    Stack stk;
    StackResult res;

    stk = stack_new(0);
    while (root != NULL || !stack_empty(stk)) {
        if (root != NULL) { /* walk down the left subtree. */
            stack_push(stk, root, &res);
            root = root->left;
        } else {
            /* no subtree to process; visit the parent node. */
            stack_pop(stk, &res);
            root = res.data;
            /* Now is the time to process this node data! */
            visitor(VISIT_ELEMENT, root->key);
            root = root->right; /* inspect the right subtree. */
        }
    };
    stack_delete(stk);
}
Пример #17
0
int main(int argc, const char * argv[])
{
    for (size_t k = 0; k < 10000; k++)
    {
        node_t *s = create_stack();
        if (stack_empty(s))
            printf("Stack is empty.\n");
        
        for (item_t i = 0; i < 1000; i++)
            push(i, s);
        
        for (item_t i = 0; i < 1000; i++)
        {
            item_t v = pop(s);
            printf("%d ", v);
        }
        printf("\n");
        free_node();
    }
    return 0;
}
Пример #18
0
/* 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;
}
Пример #19
0
int main() {
  stack_t stack;
  char buffer[BUFFER_SIZE];
  heap_init();
  stack_init(&stack);
  while (1) {
    readline(buffer, BUFFER_SIZE);
    if (strcmp(buffer, "") == 0) {
      syscall_exit(0);
    } else if (strcmp(buffer, "+") == 0) {
      perform_binop(&stack, &plus);
    } else if (strcmp(buffer, "-") == 0) {
      perform_binop(&stack, &sub);
    } else if (strcmp(buffer, "*") == 0) {
      perform_binop(&stack, &mult);
    } else if (strcmp(buffer, "/") == 0) {
      perform_binop(&stack, &divn);
    } else if (strcmp(buffer, "p") == 0) {
      if (stack_empty(&stack)) {
        printf("Stack is empty.\n");
      } else {
        printf("%d\n", *(int*)stack_top(&stack));
      }
    } else if (numeric(buffer)) {
      int x = atoi(buffer);
      int* d;
      if ((d = (int*)malloc(sizeof(int))) == NULL) {
        out_of_memory();
      } else {
        *d = x;
        if (stack_push(&stack,d) != 0) {
          out_of_memory();
        }
      }
    } else {
      printf("Bad input.\n");
    }
  }
}
Пример #20
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; 
        }
    }
}
Пример #21
0
void container_MemoryCall(enum mem_cmd cmd,md_addr_t addr, int nbytes)
{
	int i;
	
	if(containerInitialized == 1 && !stack_empty(returnAddressStack))
	{
		
		stackObject t = stack_top(returnAddressStack);

		if(cmd == Read)
		{
			t.container->totalNumberOfReads++;
			t.container->totalNumberOfBytesRead +=nbytes;
		}
		else 
		{
			t.container->totalNumberOfBytesWritten +=nbytes;
			t.container->totalNumberOfWrites++;
		}
	}

}
Пример #22
0
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");
}
Пример #23
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;
}
Пример #24
0
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);
}
Пример #25
0
int* inordertrave(node*root,int*size)
{
    stack*st=stack_init(10000);
    int*ans=malloc(sizeof(int)*10000);
    if(!root){
	*size=0;
	return ans;
    }
    int count=0;
    node*cur=root;
    while(!stack_empty(st)||cur){
	if(cur){
	    stack_push(st,cur);
	    cur=cur->left;
	}else{
	    cur=stack_pop(st);
	    ans[count++]=cur->val;
	    cur=cur->right;
	}
    }
    *size=count;
    return st;
}
Пример #26
0
void      start(int argc, char **argv, t_option option)
{
  t_map		map;
  t_stack	*stack;
  char    *p;

  p = argv[argc - 1];
  if (check_map(p) && check_exit(p) && check_player(p)) {
    init_map(&map, argv, argc, option);
    if (map.width != 0) {
      stack = s_solve(&map, NULL, NULL);
      if (stack_empty(stack) && option.c == 1) {
        map.option.c = 0;
        stack = s_solve(&map, NULL, NULL);
      }
      result(map, stack, option);
      destruct(map);
      stack_clean(stack);
    }
  }
  else
    my_putstr("La carte n'est pas valide\n");
}
Пример #27
0
void draw_stack(struct stack *stack) {
  if (stack_empty(stack)) {
    box(stack->card->frame->window, 0, 0);
    if (stock_stack(stack)) {
      if (game.passes_through_deck_left >= 1) {
        mvwprintw(stack->card->frame->window, 2, 3, "O");
      } else {
        mvwprintw(stack->card->frame->window, 2, 3, "X");
      }
    }
    wrefresh(stack->card->frame->window);
  } else {
    if (maneuvre_stack(stack)) {
      struct stack *stack_reversed_stack = stack_reverse(stack);
      for (struct stack *i = stack_reversed_stack; i; i = i->next) {
        draw_card(i->card);
      }
      stack_free(stack_reversed_stack);
    } else {
      draw_card(stack->card);
    }
  }
}
Пример #28
0
attr_eval_status_t attr_eval(attr_handle_t *attr, size_t depth_max) {
    assert(NULL != attr);

    /* Check current attribute evaluation status */
    attr_eval_status_t status = attr_get_eval_status(attr);

    if (ATTR_EVAL_UNDEF != status) return status;

    /* Create attribute ref. stack */
    stack_t stack;

    stack_init(&stack, &attr_ref_pack_pool,
        depth_max ? depth_max : STACK_SIZE_MAX);

    /* Initialise stack top with the evaluated attribute */
    attr_handle_t **attr_item = (attr_handle_t **)stack_push(&stack);

    if (NULL == attr_item) return ATTR_EVAL_ERROR;

    *attr_item = attr;

    /* Evaluate all attributes on stack */
    status = attr_eval_stack(&stack);

    /* Cleanup attribute ref. stack */
    while (!stack_empty(&stack)) {
        attr_item = (attr_handle_t **)stack_top(&stack);

        assert(NULL != attr_item);

        attr_clear_depend_eval_scheduled(*attr_item);

        stack_pop(&stack);
    }

    return status;
}
Пример #29
0
int main()
{
    char c, c1;
    unsigned i;
    short int used;

    while(scanf("%c", &c) == 1)
    {
        used = 0;
        for(i = 0; i < BN; i++)
        {
            if(c == B1[i])
            {
                used = 1;
                stack_push(c);
            }
            else if(c == B2[i])
            {
                used = 1;
                c1 = stack_front();
                if(c1 == B1[i]) stack_pop();
                else
                {
                    stack_push('!');
                    used = 0;
                    break;
                }
            }
        }

        if(!used) break;
    }

    printf("%s", stack_empty() ? "YES" : "NO");

    return 0;
}
Пример #30
0
void revtopsort(head net[], int V)
    {         /* function for reverse topological sorting */
    int i, j, k;
    node *ptr;

    init_stack();

    set_count_outdegree(net, V);

    for (i = 0; i < V; i++)
	if (!net[i].count) /* search start position of topological sort */
	    push(i);
    for (i = 0; i < V; i++)
	{
	 /* if i < V, network has cycle, case of acyclic network
	    loop must be exhausted */
	if (stack_empty())
	    {
	    printf("\nNetwork has a cycle. Sort Terminated ! ");
	    exit(1);
	    }
	else
	    {
	    j = pop();
	    printf("%c, ", int2name(j));
	    for (k = 0; k < V; k++)
		for (ptr = net[k].next; ptr; ptr = ptr->next)
		    if (ptr->vertex == j)
			{
			net[k].count--;
			if (!net[k].count)
			    push(k);
			}
	    }
	}
    }