Beispiel #1
0
int eval(linkedlist *expr, double *val) {

    int i;
    stack_t stk; /* operator stack */

    stack_init(&stk);

    for(i = 0; i < linkedlist_size(expr); i++) {
        token_t *t = linkedlist_get(expr, i);
        token_t *n2, *n1, *res;

        /* if number, push to stack: */
        if (t->type == TOKEN_NUMBER) {
            stack_push(&stk, t);
            continue;
        }

        /* all operators in the postfix expression are binary. */
        if (stack_size(&stk) < 2) {
            while(!stack_isEmpty(&stk))
                free(stack_pop(&stk));
            /* free the remaining tokens in expr: */
            while(i < linkedlist_size(expr))
                free(linkedlist_get(expr, i++));
            return -1; /* error. */
        }
        n2 = stack_pop(&stk);
        n1 = stack_pop(&stk);

        res = malloc(sizeof(token_t));
        res->type = TOKEN_NUMBER;
        res->op   = 0;
        res->num  = do_op(n1->num, n2->num, t->op);
        stack_push(&stk, res);

        free(n2);
        free(n1);
        free(t);
    }

    if (stack_size(&stk) != 1) {
        while(!stack_isEmpty(&stk)) {
            free(stack_pop(&stk));
        }
        return -1; /* error. */
    }

    *val = ((token_t *) stack_peek(&stk))->num;
    free(stack_pop(&stk));
    return 0;

}
Beispiel #2
0
int main(void)
{
    struct stack s;
    char i;

    printf("Initializing stack...\n");
    stack_init( s, 4);

    for(i='A';i<='Z';i++)
    {
        printf("push: %c\t%d\t%d\n",i,s.elements,s.kapacitas);
        // Itt nézzük a s.pData változót debuggerbol, lépjünk bele a függvénybe
        stack_push(s,i);
    }

    while(!stack_isEmpty(s))
    {
        // Itt nézzük a s.pData változót debuggerbol, lépjünk bele a függvénybe
        //és esetleg ellenõrizzük az elemszámot és a kapacitást
        printf("pop: %c\t%d\t%d\n",(char)stack_pop(s),s.elements,s.kapacitas);
    }

    // Üres stackbol kivétel: hiba (-1)
    printf("pop: %d\n",stack_pop(s));

    printf("Cleaning up stack...\n");
    stack_cleanUp(s);
    return 0;
}
Beispiel #3
0
void
*stack_pop(Stack *s) {
	if (stack_isEmpty(s)) {
		fprintf(stderr, "Stack is empty\n");
		return NULL;
	}
	return s->A[s->top--];
}
Beispiel #4
0
void exampleStack()
{
	// Use pooling for efficiency, if you don't want to use pooling
	// then comment out this line.
	pool_stack(16);

	Stack* S = newStack();

	// A stack with strings
	stack_push(S, "Out.");
	stack_push(S, "First");
	stack_push(S, "In");
	stack_push(S, "Last");

	// Peek at the top of the stack
	printf("%s\n", (char*)stack_peek(S));

	// Traverse through the stack popping each string
	while (!stack_isEmpty(S))
		printf("%s ", (char*)stack_pop(S));
	printf("\n");

	// Fill up the stack and then clear it.
	stack_push(S, "A");
	stack_push(S, "B");
	stack_push(S, "C");
	int size = S->size;
	
	stack_clear(S);
	if (stack_isEmpty(S))
		printf("The Stack had %d items but now has 0\n", size); 

	// This will clear the stack of any nodes and pool them and then free
	// the stack itself from memory
	stack_free(S);
	
	// If you're not using pooling this can be commented out. This will
	// free all pooled nodes from memory. Always call this at the end 
	// of using any Stack.
	unpool_stack();
}
Beispiel #5
0
void
stack_print(Stack *s, void(printFn)(void *)) {
	int i;
	if (stack_isEmpty(s)) {
		fprintf(stderr, "Empty Stack\n");
		return;
	}
	for (i=0;i<s->top;i++) {
		printFn(s->A[i]);
	}
	printf("\n");
}
Beispiel #6
0
/*
 *  return value:
 *      1  -- pop success
 *      0  -- pop fail due to empty stack
 *      -1 -- exception
 * */
int stack_pop(stack *pstack, bst_node **ppselem)
{
    int iRet=1;
    bst_node selem;
    LOGD("[F:%s, L:%d]\n", __FUNCTION__, __LINE__);

    if(pstack == NULL || pstack->pStackHeader == NULL || ppselem == NULL) {
        return -1;
    }
    if(stack_isEmpty(pstack)) {
        return 0;
    }

	*ppselem = *pstack->pStackHeader;
    pstack->pStackHeader--;
    pstack->nStackCurSize--;

    return iRet;
}
Beispiel #7
0
static int bst_inorderTraverse(bst *pbst)
{
    int iRet=1;
	bst_node *pCurNode=NULL;

	if(pbst==NULL || pbst->pBstRoot==NULL) {
	    return -1;
	}

	pCurNode = pbst->pBstRoot;
	do {
		//1. find most lest node, visit
		while(pCurNode!=NULL && pCurNode->pL!=NULL) {
			stack_push(&pbst->stack, pCurNode);
		    pCurNode = pCurNode->pL;
		}
		bst_visitNode(pCurNode);

		//2. if current node has right tree, stack_push, update current Node
		//   then goto step1; otherwise goto step3
		do {
			if(pCurNode->pR != NULL) {
				stack_push(&pbst->stack, pCurNode);
				pCurNode = pCurNode->pR;
				break;
			} else{
				//3. stack_pop to current node, if current has been visited, goto step3; otherwise visit
				//   goto step2
				do {
					iRet = stack_pop(&pbst->stack, &pCurNode);
				}while(iRet==1 && pCurNode->nIsVisited);
				
				if(iRet == 1) {
				    bst_visitNode(pCurNode);
				} else{
				    break;
				}
			}
		}while(1);
	}while(stack_isEmpty(&pbst->stack)==0);

	return iRet;
}
Beispiel #8
0
/*
 *  return value:
 *      1  -- pop success
 *      0  -- pop fail due to empty stack
 *      -1 -- exception
 * */
int stack_pop(stack *pstack, stack_elem *pselem)
{
    int iRet=1;
    stack_elem selem;
    printf_dbg("[F:%s, L:%d]\n", __FUNCTION__, __LINE__);

    if(pstack == NULL || pstack->pStackHeader == NULL || pstack == NULL) {
        return -1;
    }
    if(stack_isEmpty(pstack)) {
        return 0;
    }

    pselem->x= pstack->pStackHeader->x;
    pselem->y= pstack->pStackHeader->y;
    pselem->nDir= pstack->pStackHeader->nDir;
    pstack->pStackHeader--;
    pstack->nStackCurSize--;

    return iRet;
}
Beispiel #9
0
int main(void)
{
    struct stack s;
    char i;

    printf("Initializing stack...\n");
    stack_init( s, 4);

    for(i='A';i<='Z';i++)
    {
        printf("push: %c\t%d\t%d\n",i,s.elements,s.kapacitas);
        stack_push(s,i);
    }

    while(!stack_isEmpty(s))
    {
        printf("pop: %c\t%d\t%d\n",(char)stack_pop(s),s.elements,s.kapacitas);
    }
    printf("pop: %d\n",stack_pop(s));

	printf("Cleaning up stack...\n");
    stack_cleanUp(s);
    return 0;
}
int main(int argc, char *argv[])
{
	char command[32];
	int eventsNr, eventId, procId, priority;
	int i, iteration;
	TStack **eventsStacks;
	TQueue *procQ;

	// Daca nu exista destule argumente la rularea programului, atunci opreste executia
	if (argc < 3)
	{
		printf("Argumente insuficiente!\n");
		return -1;
	}

	// Seteaza fisierele de intrare si de iesire
	freopen(argv[1], "r", stdin);
	freopen(argv[2], "w", stdout);

	// Citeste numarul de event-uri si creeaza stivele lor
	fscanf(stdin, "%d", &eventsNr);

	eventsStacks = calloc(eventsNr,  sizeof(TStack*));
	for (i = 0; i < eventsNr; i++)
	{
		eventsStacks[i] = stack_new(sizeof(TProcess));
	}

	// Creeaza coada de prioritati
	procQ = queue_new(sizeof(TProcess), compare_process);

	// Citeste si executa comenzile din fisierul de intrare
	iteration = 0;

	while (fscanf(stdin, "%s", command) != EOF)
	{
		iteration++;

		if (strcmp(command, "start") == 0)
		{
			fscanf(stdin, "%d", &procId);
			fscanf(stdin, "%d", &priority);

			// Creeaza un proces
			TProcess p;
			p.id = procId;
			p.priority = priority;
			p.iteration = iteration;

			// Introduce procesul creat in coada de prioritati
			queue_push(procQ, &p);
		}
		else if (strcmp(command, "wait") == 0)
		{
			fscanf(stdin, "%d", &eventId);
			fscanf(stdin, "%d", &procId);

			// Creaza o stiva auxiliara
			TStack *aux = stack_new(sizeof(TProcess));

			// Muta procesele in stiva auxiliara pana cand procesul
			// cautat este gasit si mutat in stiva evenimentului
			TProcess *p;
			while (!queue_isEmpty(procQ))
			{
				p = queue_pop(procQ);

				if (p->id == procId)
				{
					stack_push(eventsStacks[eventId], p);
					free_process(p);
					break;
				}
				
				stack_push(aux, p);
				free_process(p);
			}

			// Muta procesele din stiva auxiliara inapoi in coada
			// de prioritati
			while (!stack_isEmpty(aux))
			{
				p = stack_pop(aux);
				queue_push(procQ, p);
				free_process(p);
			}

			// Distruge stiva auxiliara
			stack_destroy(&aux, free_process);
		}
		else if (strcmp(command, "event") == 0)
		{
			fscanf(stdin, "%d", &eventId);

			// Muta procesele din stiva evenimentului in coada
			// de prioritati
			TProcess *p;
			while (!stack_isEmpty(eventsStacks[eventId]))
			{
				p = stack_pop(eventsStacks[eventId]);
				queue_push(procQ, p);
				free_process(p);
			}
		}
		else if (strcmp(command, "end") == 0)
		{
			fscanf(stdin, "%d", &procId);

			// Creaza o stiva auxiliara
			TStack *aux = stack_new(sizeof(TProcess));

			// Muta procesele in stiva auxiliara pana cand procesul
			// cautat este gasit si sters
			TProcess *p;
			while (!queue_isEmpty(procQ))
			{
				p = queue_pop(procQ);

				if (p->id == procId)
				{
					free_process(p);
					break;
				}
				
				stack_push(aux, p);
				free_process(p);
			}

			// Muta procesele din stiva auxiliara inapoi in coada
			// de prioritati
			while (!stack_isEmpty(aux))
			{
				p = stack_pop(aux);
				queue_push(procQ, p);
				free_process(p);
			}

			// Distruge stiva auxiliara
			stack_destroy(&aux, free_process);
		}

		// Afiseaza iteratia
		printf("%d\n", iteration);

		// Afiseaza coada de prioritati
		if (!queue_isEmpty(procQ))
		{
			queue_print(procQ, print_process);
		}
		else
		{
			printf("\n");
		}

		// Afiseaza stivele
		for (i = 0; i < eventsNr; i++)
		{
			if (!stack_isEmpty(eventsStacks[i]))
			{
				printf("%d: ", i);
				stack_print(eventsStacks[i], print_process);
			}
		}

		printf("\n");
	}

	// Elibereaza memoria
	queue_destroy(&procQ, free_process);

	for (i = 0; i < eventsNr; i++)
	{
		stack_destroy(&eventsStacks[i], free_process);
	}
	free(eventsStacks);

	return 0;
}
Beispiel #11
0
 Stack* Recorrer(Maze *m, Point *input){
 	int i;
 	Stack *paux = NULL; /*pila auxiliar*/
 	Stack *pcamino = NULL; /*pila del camino seguido*/
 	EleStack *pele = NULL; /*punto donde nos encontramos*/
 	EleStack *pelepoint = NULL; /*Punto vecino*/
 	Point *ppoint = NULL;
 	Point *ppoint2 = NULL;
 	if(!m){
 		printf("Error pasando el maze\n");
 		return NULL;
 	}
 	if(!input){
 		printf("Error pasando el input\n");
 		return NULL;
 	}
 	paux = stack_ini();
 	if (!paux){
 		printf ("Error en reserva memoria paux\n");
 		return NULL;
 	}
 	pcamino = stack_ini();
 	if (!pcamino){
 		printf ("Error reserva memoria pcamino\n");
 		stack_free (paux);
 		return NULL; 
 	}
 	pele = elestack_ini();
 	if (!pele){
 		printf ("Error reserva memoria pele\n");
 		stack_free(paux);
 		stack_free(pcamino);
 		return NULL;
 	}
 	if (!elestack_setInfo(pele, input)){ /*Guardamos el punto input en pele*/
 		printf ("Error en setInfo de pele\n");
 		elestack_free(pele);
 		stack_free(paux);
 		stack_free(pcamino);
 		return NULL;
 	}
 	if(!stack_push (paux, pele)){ /*Introducimos pele en la pila auxiliar*/
 		printf("Error push del input\n");
 		elestack_free(pele);
 		stack_free(paux);
 		stack_free(pcamino);
 		return NULL;
 	}
 	elestack_free(pele); 
 	while (!stack_isEmpty(paux)){ /*mientras la pila auxiliar no esta vacia*/
 		pele = stack_pop(paux); /*extraemos el punto superior de la pila y nos "situamos" ahi*/
 		stack_push(pcamino, pele); /*Como visitamos ese punto lo introducimos en el camino*/
 		point_setSymbol(maze_getPoint(m, point_getCoordinateX((Point *)elestack_getInfo(pele)), point_getCoordinateY((Point *)elestack_getInfo(pele))), VISITADO);
 		/*Modificamos el simbolo del punto a VISITADO, lo guardamos en el laberinto original*/

		
		for(i = 0; i <= DOWN; i++){ /*Comprobamos las 4 direcciones que se pueden seguir dentro de un laberinto*/
			pelepoint = elestack_ini();
			if(!pelepoint){
				printf("Error en elestack_ini\n");
				elestack_free(pele);
	 			stack_free(paux);
	 			stack_free(pcamino);
 			return NULL;
			}
			ppoint2 = (Point*)elestack_getInfo(pele); /*Obtenemos el punto de pele*/
			if(!ppoint2){
				printf("Error al obtener el punto de pele");
				elestack_free(pelepoint);
	 			elestack_free(pele);
	 			stack_free(paux);
	 			stack_free(pcamino);
	 			return NULL;
			}
			ppoint = maze_getNeighborPoint(m, ppoint2, i); /*Obtenemos el punto vecino en la direccion que indica "i"*/
			if(!ppoint){
				printf("Error ppoint 1\n");
				elestack_free(pelepoint);
	 			elestack_free(pele);
	 			stack_free(paux);
	 			stack_free(pcamino);
	 			return NULL;
			}
			if(!elestack_setInfo(pelepoint, (void*)ppoint)){ /*Asignamos a pelepoint el punto vecino*/
				printf("Error setinfo\n");
				elestack_free(pelepoint);
	 			elestack_free(pele);
	 			stack_free(paux);
	 			stack_free(pcamino);
	 			return NULL;
			}
			if(point_getSymbol(ppoint) == SPACE){ /*Introducimos el punto en la pila auxiliar SOLO si es un SPACE*/
				if(!stack_push(paux, pelepoint)){
					printf("Error al hacer el push de pelepoint");
					elestack_free(pelepoint);
		 			elestack_free(pele);
		 			stack_free(paux);
		 			stack_free(pcamino);
		 			return NULL;
				}
			}
			else if(point_getSymbol(ppoint) == OUTPUT){ /*Si el punto es el OUTPUT, lo introduce en el camino y devuelve dicha pila*/
				stack_push(pcamino, pelepoint);
				elestack_free(pelepoint);
				elestack_free(pele);
				stack_free(paux);
				return pcamino;
			}
			elestack_free(pelepoint);
		}
 		
 		elestack_free(pele);
 	}
 	stack_free(paux);
 	stack_free(pcamino);
	return NULL;
 }
Beispiel #12
0
void processExpression (token inputToken, FILE *in, int d)
{
  /**********************************************/
  /* Declare both stack head pointers here      */
  Stack ops = stack_init( ops);
  Stack nums = stack_init( nums);
  /* Loop until the expression reaches its End */
  while (inputToken.type != EOLN)
  {
    /* The expression contains an OPERATOR */
    if (inputToken.type == OPERATOR)
    {
      /* make this a debugMode statement */
      if( d) printf ("OP:%c, " ,inputToken.op);
      // add code to perform this operation here
      //if the op is a open paren
      if( inputToken.op == '(' )
        stack_push_ch( ops, inputToken.op);
      //if the op is + or -
      else if( inputToken.op == '+' || inputToken.op == '-'){
        while( !stack_isEmpty(ops) && (stack_peek_ch(ops) == '+' 
                                  ||  stack_peek_ch(ops) == '-'
                                  ||  stack_peek_ch(ops) == '/'
                                  ||  stack_peek_ch(ops) == '*') ){
          stack_pop_eval_push( ops, nums);
        }
        stack_push_ch( ops,inputToken.op);
      }
      //if the op is * or /
      else if( inputToken.op == '*' || inputToken.op == '/'){
        while( !stack_isEmpty(ops) && (stack_peek_ch(ops) == '/' 
                                  ||  stack_peek_ch(ops) == '*') ){
          stack_pop_eval_push( ops, nums);
        }
        stack_push_ch( ops,inputToken.op);
      }
      //if the op is a closing paren
      else if( inputToken.op == ')' ){
        while( !stack_isEmpty(ops) && stack_peek_ch(ops) != '(' ){
          stack_pop_eval_push( ops, nums);
        }
        if( stack_isEmpty( ops)) printf("ERROR, no closing parenthesis!\n");
        else stack_pop_ch( ops); //pop the open parenthesis
      }
    }

    /* The expression contain a VALUE */
    else if (inputToken.type == VALUE)
    {
      /* make this a debugMode statement */
      if(d) printf ("Val: %d, ", inputToken.val);
      // add code to perform this operation here
      stack_push_i( nums, inputToken.val);
    }

    /* get next token from input */
    inputToken = getInputToken (in);
  } 

  /* The expression has reached its end */
  // add code to perform this operation here
  while( !stack_isEmpty( ops) ){
    stack_pop_eval_push( ops, nums);
  }
  printf("The top of the val stack: %d\n", stack_peek_i( nums) );
  stack_pop_i( nums);
  if( !stack_isEmpty( nums) ) printf("ERROR, leftover nums on num stack\n");
  
  stack_free( ops);
  stack_free( nums);
  printf ("\n");
}