예제 #1
0
파일: main.c 프로젝트: murph141/CTCI
void freeQueue(Queue * que)
{
  freeStack(que->enq);
  freeStack(que->deq);

  free(que);
}
예제 #2
0
/*********************** convertSubTaskRemainingStack **************************
int convertSubTaskRemainingStack(Stack stack, Out out)
Purpose:
    This function handles the rest of the stack once we've gone through 
    all of the tokens in the input. It also handles the case of a leftover
    unmatched parenthesis in the stack.
Parameters:
    I/O Stack stack	The current stack.
    O Out out	        The out structure used in the conversion.
Returns:
    stack parm - the freed stack.
    out parm - the final out structure.
Notes:
    This is a sub task of the query conversion from infix format to 
    postfix format.
*******************************************************************************/
int convertSubTaskRemainingStack(Stack stack, Out out)
{
    while (isEmpty(stack) == FALSE)	//goes through the remaining stack until empty
    {
        if (topElement(stack).iCategory == CAT_LPAREN)//if an unmatched ( is found
  	{
  	    freeStack(stack); //at this point we are done using the stack
  	    return WARN_MISSING_RPAREN; //return error
  	}	
  	addOut(out, pop(stack)); //POP and OUT the stack
    }
    freeStack(stack); //at this point we are done using the stack		
}
예제 #3
0
void assert_pop_will_return_last_element_pushed()
{
    Stack *stk = newStack(10);
    push(stk, 18);
    assert(18 == pop(stk));
    freeStack(stk);
}
예제 #4
0
str
shutdownFactoryByName(Client cntxt, Module m, str nme){
	Plant pl, plim;
	InstrPtr p;
	Symbol s;

	plim = plants + lastPlant;
	for (pl = plants; pl < plim; pl++)
		if (pl->factory ) {
			MalStkPtr stk;

			p= getInstrPtr(pl->factory,0);
			if( strcmp(nme, getFunctionId(p)) != 0) continue;
			s = findSymbolInModule(m, nme );
			if (s == NULL){
				throw(MAL, "factory.remove",
					OPERATION_FAILED " SQL entry '%s' not found",
					putName(nme));
			}
			stk = pl->stk;
			MSresetVariables(cntxt, pl->factory, stk, 0);
			shutdownFactory(cntxt, pl->factory);
			freeStack(stk);
			deleteSymbol(m,s);
			return MAL_SUCCEED;
		}
	return MAL_SUCCEED;
}
예제 #5
0
파일: eval.c 프로젝트: dougvk/CS223
// ----------------------------------------------------------- Free evaluator object
void freeEval( Eval ev )
{
  while (!isemptyStack( ev->Ators )) {
    freeOperator( topStack( ev->Ators ) );
    popStack( ev->Ators );
  }
  freeStack( ev->Ators );

  while (!isemptyStack( ev->Ands )) {
    freeOperand( topStack( ev->Ands ) );
    popStack( ev->Ands );
  }
  freeStack( ev->Ands );

  free( ev );
}
예제 #6
0
void freeContig_array ()
{
	if ( !contig_array )
	{
		return;
	}

	unsigned int i;

	for ( i = 1; i <= num_ctg; i++ )
	{
		if ( contig_array[i].seq )
		{
			free ( ( void * ) contig_array[i].seq );
		}

		if ( contig_array[i].closeReads )
		{
			freeStack ( contig_array[i].closeReads );
		}
	}

	free ( ( void * ) contig_array );
	contig_array = NULL;
}
예제 #7
0
void testLib() {
  printf("Testing stack library functions...\n");
  Stack s = createStack(3);

  printf("\nCase 1: pushing elements greater than capacity...\n");
  push(0,s); push(1,s);
  push(2,s); push(3,s);
  printStack(s);
  int success = s->top == 2;

  printf("\nCase 2: popping elements greater than length...\n");
  pop(s); pop(s);
  pop(s); pop(s);
  pop(s); pop(s);
  pop(s);
  printStack(s);
//  printf("top = %i\n",s->top);
  success = success && s->top == -1;

  printf("\nCase 3: pushing after having already enqueued and dequeued...\n");
  push(0,s); push(1,s);
  push(2,s); push(3,s);
  push(2,s); push(3,s);
  printStack(s);
//  printf("top = %i\n",s->top);
  success = success && s->top == 2;
  printf("\n");

  freeStack(s);
  if(success) printf("  ☺ success.\n");
  else printf("  ☹ failure.\n");
}
예제 #8
0
파일: calc1.c 프로젝트: shixv/test
int main(int argc,char* argv[])
{
	Stack* temp=initStack();
	Queue* postfix=initQueue();
	push(temp,'\n');
	for(int i=0;argv[1][i]!='\0';i++){
		if(isdigit(argv[1][i])){printf("%c",argv[1][i]);continue;}
		if(argv[1][i]=='('){push(temp,'(');continue;}
		if(argv[1][i]==')'){
			while(top(temp)!='('){
				printf("%c",top(temp));
				pop(temp);
			}
			pop(temp);
			continue;
		}
		if(prioritycompare(top(temp),argv[1][i])==-1)continue;
		if(prioritycompare(top(temp),argv[1][i])){
			push(temp,argv[1][i]);
			continue;
		}
		while(prioritycompare(top(temp),argv[1][i])==0){
			printf("%c",top(temp));
			pop(temp);
		}
		push(temp,argv[1][i]);
	}
	while(temp->length!=0){
		printf("%c",top(temp));
		pop(temp);
	}
	freeStack(temp);
	return 0;
}
예제 #9
0
int main() {
  int n;
  check(scanf("%d", &n) == 1, "can't read value");

  struct Node *nodesP = allocateNodes(n);

  for(size_t i = 0; i < n; i++) {
    check(scanf("%d", &nodesP[i].value) == 1, "can't read value");
    nodesP[i].key = i;
  }

  stackT *stackP = allocateStack(n);

  for(size_t i = n; i > 0; i--) {
    while(!stackIsEmpty(stackP) && stackTop(stackP).value < nodesP[i-1].value) {
      stackPop(stackP);
    }
    if(stackIsEmpty(stackP)) {
      nodesP[i-1].nearMax = n;
    } else {
      nodesP[i-1].nearMax = stackTop(stackP).key;
    }
    stackPush(stackP, nodesP[i-1]);
  }
  freeStack(stackP);

  traverseTree(nodesP, 0, n-1, TRAVERSE_POSTORDER);
  printf("\n");
  traverseTree(nodesP, 0, n-1, TRAVERSE_INORDER);
  printf("\n");

  free(nodesP);

  return 0;
}
예제 #10
0
void assert_stack_is_not_empty_when_an_element_is_pushed()
{
    Stack *stk = newStack(10);
    push(stk, 5);
    assert(FALSE == isStackEmpty(stk));
    freeStack(stk);
}
예제 #11
0
static void initStack()
{
	gint i;
	if(inStack) freeStack();
	inStack = g_malloc(Ncenters*sizeof(gboolean));
	for(i=0;i<Ncenters;i++) inStack[i] = FALSE;
}
예제 #12
0
/*
 * When a client needs to be terminated then the file descriptors for
 * its input/output are simply closed.  This leads to a graceful
 * degradation, but may take some time when the client is busy.  A more
 * forcefull method is to kill the client thread, but this may leave
 * locks and semaphores in an undesirable state.
 *
 * The routine freeClient ends a single client session, but through side
 * effects of sharing IO descriptors, also its children. Conversely, a
 * child can not close a parent.
 */
void
MCfreeClient(Client c)
{
	c->mode = FINISHCLIENT;

#ifdef MAL_CLIENT_DEBUG
	fprintf(stderr,"# Free client %d\n", c->idx);
#endif
	MCexitClient(c);

	/* scope list and curprg can not be removed, because the client may
	 * reside in a quit() command. Therefore the scopelist is re-used.
	 */
	c->scenario = NULL;
	if (c->prompt)
		GDKfree(c->prompt);
	c->prompt = NULL;
	c->promptlength = -1;
	if (c->errbuf) {
/* no client threads in embedded mode */
#ifndef HAVE_EMBEDDED
		GDKsetbuf(0);
#endif
		if (c->father == NULL)
			GDKfree(c->errbuf);
		c->errbuf = 0;
	}
	if (c->usermodule)
		freeModule(c->usermodule);
	c->usermodule = c->curmodule = 0;
	c->father = 0;
	c->login = c->lastcmd = 0;
	//c->active = 0;
	c->qtimeout = 0;
	c->stimeout = 0;
	c->user = oid_nil;
	if( c->username){
		GDKfree(c->username);
		c->username = 0;
	}
	c->mythread = 0;
	if (c->glb) {
		freeStack(c->glb);
		c->glb = NULL;
	}
	if( c->error_row){
		BBPrelease(c->error_row->batCacheid);
		BBPrelease(c->error_fld->batCacheid);
		BBPrelease(c->error_msg->batCacheid);
		BBPrelease(c->error_input->batCacheid);
		c->error_row = c->error_fld = c->error_msg = c->error_input = NULL;
	}
	if( c->wlc)
		freeMalBlk(c->wlc);
	c->wlc_kind = 0;
	c->wlc = NULL;
	MT_sema_destroy(&c->s);
	c->mode = MCshutdowninprogress()? BLOCKCLIENT: FREECLIENT;
}
예제 #13
0
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);
}
예제 #14
0
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);
}
예제 #15
0
void 
freeTreeGen(treegen_t* tg)
{
    free (tg->T);
    freeStack (tg->sp);
    freeTree (tg->tp);
    free (tg);
}
예제 #16
0
파일: tests.c 프로젝트: C8A0A697/structures
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;
}
예제 #17
0
static void expendeStack(stack *s){
    s->capacity *= 2;
    void* temp = realloc(s->value, s->capacity*s->elemSize);
    if (temp==NULL) {
        printf("ask too large memory, killed stack to save memory.\n");
        freeStack(s);
    }
    s->value = temp;
}
예제 #18
0
void
closest_pairs2graph(double *place, int n, int num_pairs, vtx_data ** graph)
{
    /* build a graph with with edges between the 'num_pairs' closest pairs in the 1-D space: 'place' */
    PairStack pairs_stack;
    initStack(&pairs_stack, num_pairs);
    find_closest_pairs(place, n, num_pairs, &pairs_stack);
    construct_graph(n, &pairs_stack, graph);
    freeStack(&pairs_stack);
}
예제 #19
0
파일: lwp.c 프로젝트: jtdreisb/os
/*
 * lwp_exit
 *
 * we build
 */
void lwp_exit() {
    lwp_procs--;
    /* saved into global so we can access after sp changes */
    stackToFree = lwp_ptable[lwp_running].stack;
    if (lwp_procs == 0) {
        SetSP(original_stack_pointer);
        /* free the stack of the last lwp */
        freeStack();
        lwp_stop();
    }
    /* cleanup sets new running proc */
    /* and it accounts for the missing proc */
    cleanup(); 

    /*SetSP(original_stack_pointer);*/
    freeStack();
    SetSP(lwp_ptable[lwp_running].sp);
    RESTORE_STATE();
    return;
}
예제 #20
0
static void
monet5_freestack(int clientid, backend_stack stk)
{
	MalStkPtr p = (ptr) stk;

	(void) clientid;
	if (p != NULL)
		freeStack(p);
#ifdef _SQL_SCENARIO_DEBUG
	mnstr_printf(GDKout, "#monet5_freestack\n");
#endif
}
예제 #21
0
/***************************** 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, &currentCustomer);
        		    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);
}
예제 #22
0
/************************** convertSubTaskRParen *******************************
int convertSubTaskRParen(Stack stack, Out out)
Purpose:
    This function handles the case of a right parenthesis token.
    The elements in the stack get outted until we find the matching 
    right parenthesis if there is one.
Parameters:
    I/O Stack stack	The current stack.
    O Out out		The out structure used in the conversion.
Returns:
    stack parm - the updated stack.
    out parm - the updated out structure.
Notes:
    This is a sub task of the query conversion from infix format to 
    postfix format.
*******************************************************************************/
int convertSubTaskRParen(Stack stack, Out out)
{
    while (isEmpty(stack) == FALSE && topElement(stack).iCategory != CAT_LPAREN)
    {
        addOut(out, pop(stack)); //POP and OUT content of the stack until left parenthesis is found
    }
    if (isEmpty(stack) == TRUE) //if we didn't find a (
    {
        freeStack(stack); //at this point we are done using the stack
  	return WARN_MISSING_LPAREN; //return error
    }
    pop(stack); //POP and get rid of (
}
예제 #23
0
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);
}
예제 #24
0
int main(int argc, char* argv[]){
   Stack A = newStack();
   Stack B = newStack();

   push(A,5); push(A,3); push(A,9); push(A,7); push(A,8);
   printStack(stdout, A);
   printf("%d\n", peek(A));
   pop(A); pop(A); pop(A);
   printf("%d\n", peek(A));
   printStack(stdout, A);
   printf("%s\n", isEmpty(A)==0?"false":"true");
   printf("%s\n", isEmpty(B)==0?"false":"true");
   push(B, 5); push(B, 3);
   push(A, 12); push(B, 13);
   printStack(stdout, A);
   printStack(stdout, B);
   popAll(A);
   printStack(stdout, B);

   freeStack(&A);
   freeStack(&B);
   return(EXIT_SUCCESS);
}
예제 #25
0
/**************************** warningExit **************************************
void warningExit(int iWarningCode, QueryResult resultM[], Stack stack)
Purpose:
    This function prints an appropriate error message and readies the 
    program to exit the current querry.
Parameters:
    I int iWarningCode	        The int code to determine the error message.
    O QueryResult resultM[]     Result array to empty.
    O Stack stack		Stack to free.
Notes:
Return value:
    resultM[] parm - Returns an empty array of boolean results for an 
		    invalid query.
    stack parm - Frees the stack for which we have no more use (since 
		this function will be followed by an early return in 
	        the evaluatePostFix function).
*******************************************************************************/
void warningExit(int iWarningCode, QueryResult resultM[], Stack stack)
{
    switch (iWarningCode)
    {
        case WARN_NOT_ENOUGH_OPER:
	    printf("\tWarning: not enough operands in query\n");
	    break;
			
        case WARN_TOO_MANY_OPER:
	    printf("\tWarning: too many operands in query\n");
	    break;
    }
    memset(resultM, 0, sizeof(resultM)); //return an empty array
    freeStack(stack);
}
예제 #26
0
void make_edge ( FILE * fp )
{
	int i = 0;
	kmer_t * node1;
	KmerSet * set;
	KmerSetsPatch = ( KmerSet ** ) ckalloc ( thrd_num * sizeof ( KmerSet * ) );

	for ( i = 0; i < thrd_num; i++ )
		{ KmerSetsPatch[i] = init_kmerset ( 1000, K_LOAD_FACTOR ); }

	nodeStack = ( STACK * ) createStack ( KMERPTBLOCKSIZE, sizeof ( KMER_PT ) );
	bal_nodeStack = ( STACK * ) createStack ( KMERPTBLOCKSIZE, sizeof ( KMER_PT ) );
	edge_c = nodeCounter = 0;
	edgeCounter = 0;

	for ( i = 0; i < thrd_num; i++ )
	{
		set = KmerSets[i];
		set->iter_ptr = 0;

		while ( set->iter_ptr < set->size )
		{
			if ( !is_kmer_entity_null ( set->flags, set->iter_ptr ) )
			{
				node1 = set->array + set->iter_ptr;
				startEdgeFromNode ( node1, fp );
			}

			set->iter_ptr ++;
		}
	}

	printf ( "%d (%d) edges %d extra nodes\n", edge_c, edgeCounter, nodeCounter );
	freeStack ( nodeStack );
	freeStack ( bal_nodeStack );
}
예제 #27
0
파일: rpn.c 프로젝트: hadfiel5/Stacks
//F*****g Recursion
void freeStack(struct stackNode *stack){

	if(stack == NULL){return;}

	struct stackNode *temp = stack;

	stack = stack->next;

	temp->next = NULL;
	free(temp);
	temp = NULL;
	
	freeStack(stack);

}
/*
	함수명: testStringReverse
	매개변수: 없음
	기능: string reverse
	예) "ABCD"를 "DCBA"의 순서로 출력
	comments
	초기에 용량 1인 stack 생성
	10개 원소를 하나씩 push
	stack이 empty가 될때까지 pop
*/
void	testStringReverse()
{
	char	str[] = "ABCD";
	int		i;

	if (createCharStack(1) != 0) return;

	for (i = 0; i < strlen(str); i++)
		push(str[i]);

	while (!isEmpty()) printf("%c", pop());
	printf("\n");

	freeStack();
}
예제 #29
0
int
main(void)
{
	struct stack *stack;
	
	stack = newStack();
	if (stack == NULL)
		exit(EXIT_FAILURE);
	
	simple(stack);
	multiple(stack);

	freeStack(stack);

	exit(EXIT_SUCCESS);
}
예제 #30
0
int main()
{
    int i;
    SqStack *s;
    s = initStack();
    for(i = 0 ; i < 20 ; i++){
        int elem = rand()%100;
		printf("%d\t", elem);
	//	StackElemType temp = {elem, NULL};
		pushStack(s, elem);
    }
	printf("\n");
    printStack(s);
	StackElemType pPopNode;
	popStack(s, &pPopNode);
	printf("%d\n", pPopNode);
	popStack(s, &pPopNode);
	printf("%d\n", pPopNode);
	
    freeStack(s);
}