예제 #1
0
int precedenceParser() {				// hlavni funkce precedencni analyzy

	tStack stack1;
	stackInit(&stack1);

	tStack stack2;
	stackInit(&stack2);

	tOpData temp;

	infix2post(&stack1, &stack2);		// prevedeni vyrazu na postfixovou notaci

	while(stackEmpty(&stack2) != true) {		// prechozeni na druhy zasobnik + kontrolni vypsani

		stackPop(&stack2, &temp);
		stackPush(&stack1, temp);
	}

	int x = reduction(&stack1, &stack2);		// provedeni redukce
	printf("Navratovy typ vyrazu: %d\n", x);

	stackDispose(&stack1);
	stackDispose(&stack2);


	return x;
}
예제 #2
0
파일: table.c 프로젝트: frickler01/turac
tableT *tableInit(int sizeTable)
{
	// allocate memory for struct
	tableT *tableP = malloc(sizeof(tableT));

	// handle allocation errors
	if (tableP == NULL)
	{
		return(NULL);
	}

	// allocate memory for struct members
	stackT *attP = stackInit(sizeTable);
	stackT *defP = stackInit(sizeTable);
	int *beatsP = malloc(sizeof(int)*sizeTable);

	// handle allocation errors
	if (attP == NULL || defP == NULL || beatsP == NULL)
	{
		return(NULL);
	}

	// link pointers
	tableP->att = attP;
	tableP->def = defP;
	tableP->beats = beatsP;

	// initialize `beats` array with values
	for (int i = 0; i < sizeTable; ++i)
	{
		tableP->beats[i] = -1;
	}

	return(tableP);
}
예제 #3
0
/*
 * canonizes all range specs within a set preserving the order
 * returns true if the set is valid after canonization; 
 * the set is valid if 
 *   - all range specs are valid and 
 *   - there is at least one range spec
 */
int
httpHdrRangeCanonize(HttpHdrRange * range, ssize_t clen)
{
    int i;
    HttpHdrRangeSpec *spec;
    HttpHdrRangePos pos = HttpHdrRangeInitPos;
    Stack goods;
    assert(range);
    assert(clen >= 0);
    stackInit(&goods);
    debug(64, 3) ("httpHdrRangeCanonize: started with %d specs, clen: %d\n", range->specs.count, clen);

    /* canonize each entry and destroy bad ones if any */
    while ((spec = httpHdrRangeGetSpec(range, &pos))) {
	if (httpHdrRangeSpecCanonize(spec, clen))
	    stackPush(&goods, spec);
	else
	    httpHdrRangeSpecDestroy(spec);
    }
    debug(64, 3) ("httpHdrRangeCanonize: found %d bad specs\n",
	range->specs.count - goods.count);
    /* reset old array */
    stackClean(&range->specs);
    stackInit(&range->specs);
    spec = NULL;
    /* merge specs:
     * take one spec from "goods" and merge it with specs from 
     * "range->specs" (if any) until there is no overlap */
    for (i = 0; i < goods.count;) {
	HttpHdrRangeSpec *prev_spec = stackTop(&range->specs);
	spec = goods.items[i];
	if (prev_spec) {
	    if (httpHdrRangeSpecMergeWith(spec, prev_spec)) {
		/* merged with current so get rid of the prev one */
		assert(prev_spec == stackPop(&range->specs));
		httpHdrRangeSpecDestroy(prev_spec);
		continue;	/* re-iterate */
	    }
	}
	stackPush(&range->specs, spec);
	spec = NULL;
	i++;			/* progress */
    }
    if (spec)			/* last "merge" may not be pushed yet */
	stackPush(&range->specs, spec);
    debug(64, 3) ("httpHdrRangeCanonize: had %d specs, merged %d specs\n",
	goods.count, goods.count - range->specs.count);
    debug(64, 3) ("httpHdrRangeCanonize: finished with %d specs\n",
	range->specs.count);
    stackClean(&goods);
    return range->specs.count > 0;
}
예제 #4
0
//方法3
bool isPalindrome(struct node *head)
{
    if (true == true)
        return true;

    struct stack *s = stackInit();

    struct node *nd = head;
    while (nd != NULL)
    {
        stackPush(s, nd);
        nd = nd->next;
    }

    while (head != NULL)
    {
        node = stackPop(s);

        if (node->data != head->data)
        {
            return false;
        }

        head = head->next;
    }

    return true;
}
예제 #5
0
HttpHdrRange *
httpHdrRangeCreate(void)
{
    HttpHdrRange *r = memAllocate(MEM_HTTP_HDR_RANGE);
    stackInit(&r->specs);
    return r;
}
int isBalanced(char *exp)
{
	int n = 10;
	stack_t s;
	stackInit(&s, n);

	int i;
	for (i = 0; i < n; i++)
	{
		if ((exp[i] == '(') || (exp[i] == '{') || (exp[i] == '['))
		{
			stackPush(&s, exp[i]);
		}
		else if ((exp[i] == ')') || (exp[i] == '}') || (exp[i] == ']'))
		{
			if (stackIsEmpty(&s) || !isPair(s.contents[s.top], exp[i]))
			{
				return -1;
			}
			else
				stackPop(&s);
		}
	}

	return stackIsEmpty(&s) ? 0 : -1;
}
/*
** This nonrecursive implementation of quicksort uses an explicit
** stack, replacing recursive calls with stack pushes(of the parameters)
** and pops, until the stack is empty. We put the larger of the two subfiles
** on the stack first to ensure the maximum stack depth for sorting N
** elements is lgN.
*/
void quick_sort(item_t *array,int left,int right)
{
	int i;
	int l,r;

	stackInit(right-left+1);
	stackPush(right);
	stackPush(left);

	while(!stackEmpty()){
		l=stackPop();
		r=stackPop();		
		if(r<=l)
			continue;

		i=partition(array,l,r);
		if(i-l > r-i){
			stackPush(i-1);
			stackPush(l);

			stackPush(r);
			stackPush(i+1);			
		}else{
			stackPush(r);
			stackPush(i+1);	

			stackPush(i-1);
			stackPush(l);	
		}
	}	
}
예제 #8
0
파일: buffer.c 프로젝트: DSil/so-project
int bufferCompleteInit(int size) {
    if(initBufferArray(size) != 0) return -1;
    if(initSemaphoresArray(size) != 0) return -1;
    if(initAccessBufferSem(size) != 0) return -1;
    if(stackInit(size) != 0) return -1;
    return 0;
}
예제 #9
0
int main(void)
{
  stack my_stack;    /* A stack  */
  int nums[10];  
  nums[0]=2;
  nums[1]=4;
  nums[2]=8; 
  
  stackInit(&my_stack, 10);

  int i;
  for (i=0;i<3;i++) {
    push(&my_stack, nums[i]);
  }


  printf("\nPopped numbers are: ");

  while (!checkEmpty(&my_stack)) {
    printf("%d\n", pop(&my_stack));
  }

  printf("\n");

  stackDestroy(&my_stack);

  return 0;
}
예제 #10
0
void kThread::initializeMainUT(bool isDefaultKT) {
    /*
     * if defaultKT, then create a stack for mainUT.
     * kernel thread's stack is assigned to initUT.
     */
    if (slowpath(isDefaultKT)) {
        mainUT = uThread::create(defaultStackSize);
        /*
         * can't use mainUT->start as mainUT should not end up in
         * the Ready Queue. Thus, the stack pointer shoud be initiated
         * directly.
         */
        mainUT->stackPointer = (vaddr) stackInit(mainUT->stackPointer, (ptr_t) uThread::invoke,
                (ptr_t) kThread::defaultRun, (void*)this, nullptr, nullptr); //Initialize the thread context
        mainUT->state = uThread::State::READY;
    } else {
        /*
         * Default function takes up the default kernel thread's
         * stack pointer and run from there
         */
        mainUT = uThread::createMainUT(*localCluster);
        currentUT = mainUT;
        mainUT->state = uThread::State::RUNNING;
    }

    //Default uThreads are not being counted
    uThread::totalNumberofUTs--;
}
예제 #11
0
파일: tess.c 프로젝트: OpenCPN/OpenCPN
//	Starting with a valid triangulation, uses the Edge Flip algorithm to
//	refine the triangulation into a Constrained Delaunay Triangulation.
void tessMeshRefineDelaunay( TESSmesh *mesh, TESSalloc *alloc )
{
	// At this point, we have a valid, but not optimal, triangulation.
	// We refine the triangulation using the Edge Flip algorithm
	//
	//  1) Find all internal edges
	//	2) Mark all dual edges
	//	3) insert all dual edges into a queue

	TESSface *f;
	EdgeStack stack;
	TESShalfEdge *e;
	int maxFaces = 0, maxIter = 0, iter = 0;

	stackInit(&stack, alloc);

	for( f = mesh->fHead.next; f != &mesh->fHead; f = f->next ) {
		if ( f->inside) {
			e = f->anEdge;
			do {
				e->mark = EdgeIsInternal(e); // Mark internal edges
				if (e->mark && !e->Sym->mark) stackPush(&stack, e); // Insert into queue
				e = e->Lnext;
			} while (e != f->anEdge);
			maxFaces++;
		}
	}

	// The algorithm should converge on O(n^2), since the predicate is not robust,
	// we'll save guard against infinite loop.
	maxIter = maxFaces * maxFaces;

	// Pop stack until we find a reversed edge
	// Flip the reversed edge, and insert any of the four opposite edges
	// which are internal and not already in the stack (!marked)
	while (!stackEmpty(&stack) && iter < maxIter) {
		e = stackPop(&stack);
		e->mark = e->Sym->mark = 0;
		if (!tesedgeIsLocallyDelaunay(e)) {
			TESShalfEdge *edges[4];
			int i;
			tessMeshFlipEdge(mesh, e);
			// for each opposite edge
			edges[0] = e->Lnext;
			edges[1] = e->Lprev;
			edges[2] = e->Sym->Lnext;
			edges[3] = e->Sym->Lprev;
			for (i = 0; i < 4; i++) {
				if (!edges[i]->mark && EdgeIsInternal(edges[i])) {
					edges[i]->mark = edges[i]->Sym->mark = 1;
					stackPush(&stack, edges[i]);
				}
			}
		}
		iter++;
	}

	stackDelete(&stack);
}
예제 #12
0
파일: hp.cpp 프로젝트: kavon/SALSA
/*
 * Adds a thread to the HPReord list.
 * hpData - An HPData object created by initHPData
 */
void threadRegister(HPData hpData) {
	int i;
	//init record
	HPRecord* record = (HPRecord*) malloc(sizeof(HPRecord) + (sizeof(void*)
			* hpData->HP_COUNT));
	assert(record != NULL);
	record->next = NULL;
	for (i = 0; i < hpData->HP_COUNT; i++) {
		record->hp[i] = NULL;
	}

	//init thread local struct
	HPLocal res = (HPLocal) malloc(sizeof(HPLocalT));
	assert(res != NULL);

	res->localRecord = record;

	int
			stackSize = hpData->THREAD_COUNT * hpData->HP_COUNT
					> hpData->REC_COUNT ? hpData->THREAD_COUNT
					* hpData->HP_COUNT : hpData->REC_COUNT;

	res->rlist = stackInit(stackSize);
	res->temp = stackInit(stackSize);
	res->plist = setInit(stackSize);
	res->hpData = hpData;

	if (head == NULL && CAS((unsigned long*) ((void*) &head), 0,
			(unsigned long) ((void*) record))) {
		res->HPRecHead = record;
	} else {
		res->HPRecHead = head;
		//add record to list
		while (1) {
			HPRecord* last = head;
			while (last->next != NULL)
				last = last->next;
			if (CAS((unsigned long*) ((void*) &(last->next)), 0,
					(unsigned long) ((void*) record)))
				break;
		}
	}
	localHPData = res;
}
int calculate(char *exp)
{
	int n = strlen(exp);
	stack_t s;
	stackInit(&s, n);

    int j, result;

	int i, first, second;
	for (i = 0; i < n; i++)
	{
		if ((exp[i] >= '0') && (exp[i] <= '9'))
		{
            stackPush(&s, exp[i] - '0');
		}
		else
		{
			if (s.top < 1)
            {
				fprintf(stderr, "Invalid expression: values not sufficient\n");
				return INT_MIN;
            }
			second = stackPop(&s);
			first = stackPop(&s);
			switch (exp[i])
			{
				case '+':
				    result = first + second;
					stackPush(&s, result);
					break;
				case '-':
					stackPush(&s, first - second);
					break;
				case '*':
					stackPush(&s, first * second);
					break;
				case '/':
					stackPush(&s, first / second);
					break;
			}
		}
		for (j = 0; j <= i; j++)
        {
           printf("Element %d: %d\n", j, s.contents[j]);
        }
        printf("%d\n", s.top);
	}

	if (s.top == 0)
		return s.contents[s.top];
	fprintf(stderr, "Invalid expression: too many values");
	return INT_MIN;
}
예제 #14
0
파일: tess.c 프로젝트: Aidoru/openscad
/*
	Starting with a valid triangulation, uses the Edge Flip algorithm to
	refine the triangulation into a Constrained Delaunay Triangulation.
*/
int tessMeshRefineDelaunay( TESSmesh *mesh, TESSalloc *alloc )
{
	/* At this point, we have a valid, but not optimal, triangulation.
		 We refine the triangulation using the Edge Flip algorithm */

/*
	 1) Find all internal edges
	 2) Mark all dual edges
	 3) insert all dual edges into a queue
*/
	TESSface *f;
	EdgeStack stack;
	TESShalfEdge *e;
	TESShalfEdge *edges[4];
	stackInit(&stack, alloc);
	for( f = mesh->fHead.next; f != &mesh->fHead; f = f->next ) {
		if ( f->inside) {
			e = f->anEdge;
			do {
				e->mark = EdgeIsInternal(e); /* Mark internal edges */
				if (e->mark && !e->Sym->mark) stackPush(&stack, e); /* Insert into queue */
				e = e->Lnext;
			} while (e != f->anEdge);
		}
	}
	
	// Pop stack until we find a reversed edge
	// Flip the reversed edge, and insert any of the four opposite edges
	// which are internal and not already in the stack (!marked)
	while (!stackEmpty(&stack)) {
		e = stackPop(&stack);
		e->mark = e->Sym->mark = 0;
		if (!tesedgeIsLocallyDelaunay(e)) {
			int i;
			tessMeshFlipEdge(mesh, e);
			// for each opposite edge
			edges[0] = e->Lnext;
			edges[1] = e->Lprev;
			edges[2] = e->Sym->Lnext;
			edges[3] = e->Sym->Lprev;
			for (i=0;i<3;i++) {
				if (!edges[i]->mark && EdgeIsInternal(edges[i])) {
					edges[i]->mark = edges[i]->Sym->mark = 1;
					stackPush(&stack, edges[i]);
				}
			}
		}
	}
	
	stackDelete(&stack);

	return 1;
}
예제 #15
0
파일: trace.c 프로젝트: AmeyaVS/trace-ninja
int main( int argc, char *argv[] )
{
  FILE *tracef;
  char type;
  unsigned int address;

  if (argc != 2) {

    printf("Usage: pvtrace <image>\n\n");
    exit(-1);

  }

  initSymbol( argv[1] );
  stackInit();

  tracef = fopen("trace.txt", "r");

  if (tracef == NULL) {
    printf("Can't open trace.txt\n");
    exit(-1);
  }

  while (!feof(tracef)) {

    fscanf( tracef, "%c0x%x\n", &type, &address );

    if        (type == 'E') {

      /* Function Entry */

      addSymbol( address );

      addCallTrace( address );

      stackPush( address );

    } else if (type == 'X') {

      /* Function Exit */

      (void) stackPop();

    }

  }

  emitSymbols();

  fclose( tracef );
  
  return 0;
}
예제 #16
0
ERROR interpret(SYMBOL_TABLE* table)
{
	STACK_PTR stack;
	ERROR err;
	stack = gcMalloc(sizeof(struct STACK));
	stackInit(stack);
	
	/// ----- POZNAMKA ----- 
	err = recursive_interpret(table->curr,stack);

	stackFree(stack);
	gcFree(stack);
	return err;
}
예제 #17
0
파일: stackdemo.c 프로젝트: eclipseCrow/adt
int main() {
        Stack *s = stackInit();
        push(s, 4);
        push(s, 2);
        push(s, 6);
        push(s, 9);
        push(s, 7);
        while (!isStackEmpty(s)) {
                fprintf(stdout, "%d\n", pop(s));
        }
	deleteStack(s);

        return 0;
}
예제 #18
0
int countSlots(OperandStack* p1,int argNumber) {
    OperandStack* p2;
    Operand operand;
    int i, slots = 0;

    stackInit(&p2);
    for (i = 0; i < argNumber; i++, slots++) {
        operand = popOperand(&p1);
        pushOperand(&p2, operand);
        if (operand.type32_64 == CAT2) slots++;
    }
    for (i = 0; i < argNumber; i++) {
        pushOperand(&p1, popOperand(&p2));
    }
    return slots;
}
char findMajority(CDataType m[], unsigned size, CDataType *majority)
{ unsigned i, cnt;
  stackInit();
  for (stackPush(m[0]), i = 1; i < size; i++) {
    if (stackIsEmpty())
      stackPush(m[i]);
    else if (stackTop() == m[i])
      stackPush(m[i]);
    else
      stackPop();
  }
  if (stackIsEmpty()) return 0;
  for (*majority = stackPop(), i = cnt = 0; i < size; i++)
    if (m[i] == *majority)
      cnt++;
  return(cnt > size / 2);
}
void traverse(int k,void (*visit)(int))
{
	link_t x;
	int t;
	
	stackInit(100);
	stackPush(k);

	while(!stackEmpty()){
		t=stackPop();
		if(visited[t]==0)
			visit(t);
		visited[t]=1;

		Push(adj[t]);
	}
}
int customerInit(Customer *c, char id[])
{
    
    if(c==NULL||id==NULL)
    {
                         printf("Error: Invalid customer or invalid customer id.");
                         return -1;
    }
    
    strcpy(c->id, id);
    c->basket = newStack();
    stackInit(c->basket);
    c->total=0;
    c->quantity = 0;
    
    return 0;
}
int printBill(Customer *c)
{
    
    if(c==NULL)
    {
                         printf("Error: No customer to process.");
                         return -1;
    }
    
    int i;
    time_t invoiceTime;
    basketItem *b;
    Stack *temp=newStack();
    
    stackInit(temp);
    
    clearScreen();
    
    time(&invoiceTime);
    
    printf("\n\tInvoice id: %s\n\n\tDate/Time: %s\n\n", c->id, ctime(&invoiceTime));
    
    printf("\t| Code\t Item\t\t Price\t Qty.\t Subtotal\t\n");
    printLine();
    
    while(stackIsEmpty(c->basket)==0)
    {
             
                                     b=stackPop(c->basket);
                                     if(b!=NULL)
                                     {
                                         printItem(b);
                                         c->total+=subTotal(b);
                                         stackPush(temp, b);
                                     }
    }
    printf("\n\tTotal number of items: %d", c->quantity);
    printf("\n\n\tTotal Payable: %0.2f\n", c->total);
    printLine();
    
    while(stackIsEmpty(temp)==0)
                                stackPush(c->basket, stackPop(temp));
                                
    return 0;
}
예제 #23
0
/*
** Konverzní funkce infix2postfix.
** Ète infixový výraz ze vstupního øetìzce infExpr a generuje
** odpovídající postfixový výraz do výstupního øetìzce (postup pøevodu
** hledejte v pøedná¹kách nebo ve studijní opoøe). Pamì» pro výstupní øetìzec
** (o velikosti MAX_LEN) je tøeba alokovat. Volající funkce, tedy
** pøíjemce konvertovaného øetìzce, zajistí korektní uvolnìní zde alokované
** pamìti.
**
** Tvar výrazu:
** 1. Výraz obsahuje operátory + - * / ve významu sèítání, odèítání,
**    násobení a dìlení. Sèítání má stejnou prioritu jako odèítání,
**    násobení má stejnou prioritu jako dìlení. Priorita násobení je
**    vìt¹í ne¾ priorita sèítání. V¹echny operátory jsou binární
**    (neuva¾ujte unární mínus).
**
** 2. Hodnoty ve výrazu jsou reprezentovány jednoznakovými identifikátory
**    a èíslicemi - 0..9, a..z, A..Z (velikost písmen se rozli¹uje).
**
** 3. Ve výrazu mù¾e být pou¾it pøedem neurèený poèet dvojic kulatých
**    závorek. Uva¾ujte, ¾e vstupní výraz je zapsán správnì (neo¹etøujte
**    chybné zadání výrazu).
**
** 4. Ka¾dý korektnì zapsaný výraz (infixový i postfixový) musí být uzavøen
**    ukonèovacím znakem '='.
**
** 5. Pøi stejné prioritì operátorù se výraz vyhodnocuje zleva doprava.
**
** Poznámky k implementaci
** -----------------------
** Jako zásobník pou¾ijte zásobník znakù tStack implementovaný v pøíkladu c202.
** Pro práci se zásobníkem pak pou¾ívejte výhradnì operace z jeho rozhraní.
**
** Pøi implementaci vyu¾ijte pomocné funkce untilLeftPar a doOperation.
**
** Øetìzcem (infixového a postfixového výrazu) je zde my¹leno pole znakù typu
** char, jen¾ je korektnì ukonèeno nulovým znakem dle zvyklostí jazyka C.
**
** Na vstupu oèekávejte pouze korektnì zapsané a ukonèené výrazy. Jejich délka
** nepøesáhne MAX_LEN-1 (MAX_LEN i s nulovým znakem) a tedy i výsledný výraz
** by se mìl vejít do alokovaného pole. Po alokaci dynamické pamìti si v¾dycky
** ovìøte, ¾e se alokace skuteènì zdraøila. V pøípadì chyby alokace vra»te namísto
** øetìzce konstantu NULL.
*/
char* infix2postfix (const char* infExpr) {
    char *postExpr = malloc(MAX_LEN * sizeof(char));
    unsigned postLen = 0;

    tStack stack;
    stackInit(&stack);

    char tmp;
    for(unsigned i = 0; (tmp = infExpr[i]) != '='; i++) {
        switch(tmp) {
        case '+':
        case '-':
        case '*':
        case '/':
            // Zpracuj operator
            doOperation(&stack, tmp, postExpr, &postLen);
            break;
        case '(':
            // Pridaj lavu zatvorku do zasobniku.
            stackPush(&stack, '(');
            break;
        case ')':
            // Zpracuj pravu zatvorku.
            untilLeftPar(&stack, postExpr, &postLen);
            break;
        default:
            // Zpracuj hodnotu.
            // isalnum()
            if((tmp >= '0' && tmp <='9') || (tmp >= 'a' && tmp <= 'z') || (tmp >= 'A' && tmp <= 'Z'))
                postExpr[postLen++] = tmp;
            break;
        }
    }
    while(!stackEmpty(&stack)) {
        stackTop(&stack, &tmp);
        postExpr[postLen++] = tmp;
        stackPop(&stack);
    }
    postExpr[postLen++] = '=';
    postExpr[postLen] = '\0';

    return postExpr;
}
예제 #24
0
int main(int argc, char *argv[])
{
  struct input in;
  in.line = 1;
  in.newline = false;

  if (argc != 2)
  {
    printErr("Spatny pocet parametru.\n");
    return EXIT_INTERNAL_ERROR;
  }

  if (!(in.file = fopen(argv[1], "r")))
  {
    printf("Soubor se nepodarilo otevrit.\n");
    return EXIT_INTERNAL_ERROR;
  }

  tListOfInstr ilist;
  listInit(&ilist);
  stack s;
  stackInit(&s);
  btree table;
  SymbolTableInit(&table);

  printDebug("=========== PARSER ============\n");
  int retValInterpret = EXIT_SUCCESS;
  int retVal = parser(&in, &table, &ilist, &s);

  printDebug("========== INTERPRET ==========\n");
  if (retVal == EXIT_SUCCESS) retValInterpret = interpret(&ilist);

  SymbolTableDispose(&table);
  listFree(&ilist, retVal);
  fclose(in.file);

  if (retValInterpret == EXIT_TYPE_ERROR) printErr("TYPE ERROR: You are trying to input boolean. Sorry I can't agree with that.\n");
  if (retValInterpret == EXIT_READ_STDIN_ERROR) printErr("READ STDIN ERROR: Your input is of a wrong data type.\n");
  if (retVal != EXIT_SUCCESS) return retVal;
  return retValInterpret;
}
예제 #25
0
/**
 * Hlavní program.
 */
int main(void) {
   tStack s;
   stackInit(&s);
   tiskniZasobnik(&s);
   prazdnyZasobnik(&s);

   stackPush(&s, 1);
   tiskniZasobnik(&s);
   prazdnyZasobnik(&s);

   stackPush(&s, 2);
   stackPush(&s, 3);
   stackPush(&s, 4);

   tiskniZasobnik(&s);
   prazdnyZasobnik(&s);

   int pom = 0;
   stackTop(&s, &pom);
   stackPop(&s);
   printf("Vyjmuli jsme: %d\n",pom);

   stackTop(&s, &pom);
   stackPop(&s);
   printf("Vyjmuli jsme: %d\n",pom);

   tiskniZasobnik(&s);
   prazdnyZasobnik(&s);


   stackDelete(&s);

   tiskniZasobnik(&s);
   prazdnyZasobnik(&s);


   return EXIT_SUCCESS;
}
예제 #26
0
int main() {
	stack s1;

	stackInit(&s1);

	stackPush(&s1, "Jag");
	stackPush(&s1, "Hans");
	stackPush(&s1, "John");
	stackPush(&s1, "500");

	printf("stack length: %d\n", stackLength(&s1));

	printf("stack popped: %s\n", stackPop(&s1));
	printf("stack popped: %s\n", stackPop(&s1));
	printf("stack popped: %s\n", stackPop(&s1));
	printf("stack length: %d\n", stackLength(&s1));

	// how to convert an int to a string?
	char *str = malloc(10 * sizeof(char));
	int num = 1250;
	sprintf(str, "%d", num);
	stackPush(&s1, str);

	str = malloc(10 * sizeof(char));
	num = 1500;
	sprintf(str, "%d", num);
	stackPush(&s1, str);

	printf("stack length: %d\n", stackLength(&s1));
	printf("stack popped: %s\n", stackPop(&s1));
	printf("stack popped: %s\n", stackPop(&s1));
	printf("stack popped: %s\n", stackPop(&s1));

	stackDestroy(&s1);
	printf("stack length: %d\n", stackLength(&s1));

	return 0;
}
예제 #27
0
         /* Zavolá funkci stackInit a v pøípadì, ¾e nebyla øe¹ena, ohlásí to. */
void use_stack_init ( tStack* ptrstack ) {
	solved = 1;
	stackInit( ptrstack );
	if ( ! solved )
		printf("[W] Funkce stackInit nebyla implementována.\n");
}
예제 #28
0
/* 
** Konverzní funkce infix2postfix.
** Ète infixový výraz ze vstupního øetìzce infExpr a generuje
** odpovídající postfixový výraz do výstupního øetìzce (postup pøevodu
** hledejte v pøedná¹kách nebo ve studijní opoøe). Pamì» pro výstupní øetìzec
** (o velikosti MAX_LEN) je tøeba alokovat. Volající funkce, tedy
** pøíjemce konvertovaného øetìzce, zajistí korektní uvolnìní zde alokované
** pamìti.
**
** Tvar výrazu:
** 1. Výraz obsahuje operátory + - * / ve významu sèítání, odèítání,
**    násobení a dìlení. Sèítání má stejnou prioritu jako odèítání,
**    násobení má stejnou prioritu jako dìlení. Priorita násobení je
**    vìt¹í ne¾ priorita sèítání. V¹echny operátory jsou binární
**    (neuva¾ujte unární mínus).
**
** 2. Hodnoty ve výrazu jsou reprezentovány jednoznakovými identifikátory
**    a èíslicemi - 0..9, a..z, A..Z (velikost písmen se rozli¹uje).
**
** 3. Ve výrazu mù¾e být pou¾it pøedem neurèený poèet dvojic kulatých
**    závorek. Uva¾ujte, ¾e vstupní výraz je zapsán správnì (neo¹etøujte
**    chybné zadání výrazu).
**
** 4. Ka¾dý korektnì zapsaný výraz (infixový i postfixový) musí být uzavøen 
**    ukonèovacím znakem '='.
**
** 5. Pøi stejné prioritì operátorù se výraz vyhodnocuje zleva doprava.
**
** Poznámky k implementaci
** -----------------------
** Jako zásobník pou¾ijte zásobník znakù tStack implementovaný v pøíkladu c202. 
** Pro práci se zásobníkem pak pou¾ívejte výhradnì operace z jeho rozhraní.
**
** Pøi implementaci vyu¾ijte pomocné funkce untilLeftPar a doOperation.
**
** Øetìzcem (infixového a postfixového výrazu) je zde my¹leno pole znakù typu
** char, jen¾ je korektnì ukonèeno nulovým znakem dle zvyklostí jazyka C.
**
** Na vstupu oèekávejte pouze korektnì zapsané a ukonèené výrazy. Jejich délka
** nepøesáhne MAX_LEN-1 (MAX_LEN i s nulovým znakem) a tedy i výsledný výraz
** by se mìl vejít do alokovaného pole. Po alokaci dynamické pamìti si v¾dycky
** ovìøte, ¾e se alokace skuteènì zdraøila. V pøípadì chyby alokace vra»te namísto
** øetìzce konstantu NULL.
*/
char* infix2postfix (const char* infExpr) {
	char *postExpr;
	unsigned postLen = 0;
	int stringSize;
	tStack *s;

	// alokace vystupniho retezce
	if ((postExpr = (char *) malloc(MAX_LEN)) == NULL) {
		return NULL;
	}

	// alokace zasobniku
	if ((s = malloc(sizeof(char *) * STACK_SIZE)) == NULL) {
		free(postExpr);
		return NULL;
	}

	// inicializace zasobniku
	stackInit(s);

	// zjisteni delky retezce
	stringSize = snprintf(NULL, 0, "%s", infExpr);

	// zpracovani retezce
	for (unsigned i = 0; i <= stringSize; i++) {
		if (
		    (infExpr[i] >= '0' && infExpr[i] <= '9') ||
		    (infExpr[i] >= 'A' && infExpr[i] <= 'Z') ||
		    (infExpr[i] >= 'a' && infExpr[i] <= 'z')
		   ) {
			// nacteni alfanumerickeho znaku do vystupniho retezce
			postExpr[postLen] = infExpr[i];
			postLen++;
		} else if (infExpr[i] == '(') {
			// je-li zpracovana polozka leva zavorka, umistim na
			// vrchol zasobniku
			stackPush(s, infExpr[i]);
		} else if (infExpr[i] == ')') {
			// Je-li zpracovávanou polo¾kou pravá závorka, 
			// odebíram z vrcholu zasobniku polo¾ky a dávam
			// na konec výstupního øetìzce a¾ narazim na levou
			// závorku.
			untilLeftPar(s, postExpr, &postLen);
		} else if (infExpr[i] == '=') {
			// Je-li zpracovávanou polo¾kou '=', pak postupnì 
			// odstraòuju prvky z vrcholu zásobníku a pøidávam na
			// konec øetìzce, a¾ se zásobník zcela vyprázdní.
			// Na konec se pøidá rovnítko, jako omezovaè výrazu.
			while (!stackEmpty(s)) {
				stackTop(s, &postExpr[postLen]);
				postLen++;
				stackPop(s);
			}
				postExpr[postLen] = '=';
				postLen++;
				postExpr[postLen] = '\0';
		} else {
			// zpracovani operatoru
			doOperation(s, infExpr[i], postExpr, &postLen);
		}
	}
	
	free(s);

	return postExpr;
}
예제 #29
0
/*===========================================================================*
 *				main                                         *
 *===========================================================================*/
int main(int argc, char **argv)
{
/* This is the main routine of this service. The main loop consists of 
 * three major activities: getting new work, processing the work, and
 * sending the reply. The loop never terminates, unless a panic occurs.
 */
  message m_in;
  int result;                 
  
  sef_startup();

	vector_init(&sem_list);
    Qvector_init(&waiting_list);
	stackInit(&sem_stack,5);

  /* Main loop - get work and do it, forever. */         
  while (TRUE) {              


	
      /* Wait for incoming message, sets 'callnr' and 'who'. */
    get_work(&m_in);
	//printf("SEM recieved message %d\n",callnr);
      if (is_notify(callnr)) {
          printf("SEM: warning, got illegal notify from: %d\n", m_in.m_source);
          result = EINVAL;
          goto send_reply;
      }

	int arg = m_in.m1_i1;
	switch(callnr)
	{	
		case SEM_INIT:
			//printf("Sem_init called, semaphore size 3%d.\n",arg);			
			result = sem_init(arg);			
			break;
		case SEM_UP:
			//printf("Sem_up called on semaphore %d.\n",arg);
			result = sem_up(arg);
			break;
		case SEM_DOWN:
			//printf("Sem_down called on semaphore %d. source: %d\n",arg,who_e);
			result  = sem_down(arg,m_in.m_source);
			break;
		case SEM_RELEASE:
			//printf("Sem_release called on semaphore %d.\n",arg);
			result = sem_release(arg);
			break;
		default: 
          		printf("SEMAPHORE: warning, got illegal request from %d\n", m_in.m_source);
          		result = EINVAL;
	}	



send_reply:
    	/* Finally send reply message, unless disabled. */
    	if (result != EDONTREPLY) {
        	m_in.m_type = result;  		/* build reply message */
			reply(who_e, &m_in);		/* send it away */
      }
	}
	Qvector_free(&waiting_list);
	vector_free(&sem_list);
	return(OK);				/* shouldn't come here */
}
예제 #30
0
int main() {
   TTable table;
   tableInit(&table);

   printf("\nTabulka by mela byt prazdna: \n");
   tablePrintOrder(table);
   printf("\n----------------------------\n");

   tableInsertFunction(&table, strCreateString("func1"));
   functionInsertVar(table.lastAddedFunc, strCreateString("var1func1"));
   functionInsertVar(table.lastAddedFunc, strCreateString("var2func1"));
   functionInsertVar(table.lastAddedFunc, strCreateString("var3func1"));

   printf("\nJedna funkce: \n");
   tablePrintOrder(table);
   printf("\n----------------------------\n");

   tableInsertFunction(&table, strCreateString("func2"));
   functionInsertVar(table.lastAddedFunc, strCreateString("var1func2"));
   functionInsertVar(table.lastAddedFunc, strCreateString("var2func2"));
   functionInsertVar(table.lastAddedFunc, strCreateString("var3func2"));

   printf("\nDve funkce: \n");
   tablePrintOrder(table);
   printf("\n----------------------------\n");

   tableInsertFunction(&table, strCreateString("func3"));
   functionInsertVar(table.lastAddedFunc, strCreateString("var1func3"));
   functionInsertVar(table.lastAddedFunc, strCreateString("var2func3"));
   functionInsertVar(table.lastAddedFunc, strCreateString("var3func3"));

   printf("\nVsechny: \n");
   tablePrintOrder(table);
   printf("\n----------------------------\n");

   // test heldani
   {

      TFunction *fceSearch;

      printf("\nObsahuje tabulka funkci %s? \t", "func1");
      fceSearch = tableSearchFunction(&table, strCreateString("func1"));
      if(fceSearch != NULL) {
         printf("ANO\n");
         printf("   Obsahuje funkce promenou %s?\t", "var1func1");
         if(functionSearchVar(fceSearch, strCreateString("var1func1")) != NULL)
            printf("ANO");
         else
            printf("NE");
      } else
         printf("NE\n");

      printf("\nObsahuje tabulka funkci %s? \t", "funcX");
      fceSearch = tableSearchFunction(&table, strCreateString("funcX"));
      if(fceSearch != NULL) {
         printf("ANO\n");
         printf("   Obsahuje funkce promenou %s?\t", "var1func1");
         if(functionSearchVar(fceSearch, strCreateString("var1func1")) != NULL)
            printf("ANO");
         else
            printf("NE");
      } else
         printf("NE\n");

      printf("\n----------------------------\n");
   }


   // test zásobníku:
   printf("TEST ZASOBNIKU:\n");
   printf("----------------------------\n");

   TStack s;
   stackInit(&s);

   prazdnyStack(s);

   TFunction *fce = tableSearchFunction(&table, strCreateString("func2"));
   TVar *id = functionSearchVar(fce, strCreateString("var1func2"));
   stackPush(&s, (void*)id);

   prazdnyStack(s);
   tiskniStack(&s);

   id = functionSearchVar(fce, strCreateString("var2func2"));
   stackPush(&s, (void*)id);
   tiskniStack(&s);
   id = functionSearchVar(fce, strCreateString("var3func2"));
   stackPush(&s, (void*)id);
   tiskniStack(&s);
   id = functionSearchVar(fce, strCreateString("var1func2"));
   stackPush(&s, (void*)id);
   tiskniStack(&s);


   TVar *data = (TVar*)stackTopPop(&s);
   if (data != NULL)  printf("Vybráno ze zásobníku: %s\n",data->name);
   else printf("Ukazatel je nulový! \n");
   prazdnyStack(s);

   data = (TVar*)stackTopPop(&s);
   if (data != NULL)  printf("Vybráno ze zásobníku: %s\n",data->name);
   else printf("Ukazatel je nulový! \n");
   prazdnyStack(s);

   data = (TVar*)stackTopPop(&s);
   if (data != NULL)  printf("Vybráno ze zásobníku: %s\n",data->name);
   else printf("Ukazatel je nulový! \n");
   prazdnyStack(s);

   tiskniStack(&s);
   stackDelete   (&s);
   prazdnyStack(s);
   tiskniStack(&s);

   data = (TVar*)stackTopPop(&s);
   if (data != NULL)  printf("Vybráno ze zásobníku: %s\n",data->name);
   else printf("Ukazatel je nulový! \n");
   printf("----------------------------\n");

   // test seznamu:
   printf("TEST SEZNAMU:\n");
   printf("----------------------------\n");


   TList L;
   listInit (&L);
   id = functionSearchVar(fce, strCreateString("var1func2"));
   TLItem *uk2 = listGetActive (&L);
   listSetActive(&L, uk2);
   aktivniList(L);

   listInsertLast(&L, id);
   tiskniList(&L);

   void *uk4 = listCopyLast(&L);
   printf("Zkopírováno:  %s\n",((TVar*)uk4)->name);


   aktivniList(L);
   listFirst(&L);
   tiskniList(&L);

   listLast(&L);
   tiskniList(&L);

   id = functionSearchVar(fce, strCreateString("var2func2"));
   listPostInsert(&L, id);
   tiskniList(&L);

   id = functionSearchVar(fce, strCreateString("var3func2"));
   listInsertLast(&L, id);
   tiskniList(&L);


   id = functionSearchVar(fce, strCreateString("var1func2"));
   listInsertLast(&L, id);
   tiskniList(&L);

   listFirst(&L);
   listSucc(&L);
   TLItem *uk = listGetActive (&L);
   tiskniList(&L);

   listLast(&L);
   tiskniList(&L);

   listSetActive(&L, uk);
   tiskniList(&L);

   aktivniList(L);
   listDeleteFirst(&L);
   tiskniList(&L);

   void *uk3 = listCopyLast(&L);
   printf("Zkopírováno:  %s\n",((TVar*)uk3)->name);
   listSucc(&L);
   tiskniList(&L);

   listActualize(&L, uk3);
   tiskniList(&L);

   listDispose (&L);
   printf("----------------------------\n");
   // konec testu seznamu

   printf("\nSmazu: \n");
   tableClear(&table);
   tablePrintOrder(table);
   printf("\n----------------------------\n");
}