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;
}
Ejemplo n.º 2
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;
}
Ejemplo n.º 3
0
int getOccurence(char* funcName){
	//printf("getOccurence\n");
	if(symStack == NULL){
		return 0;
	}
	void* backup = stackNew(sizeof(funcVars*));
	int occ = 0;
	while(!(stackIsEmpty(symStack))){
		funcVars* pk = (funcVars*) malloc (sizeof(funcVars));
		stackPeek(symStack, &pk);
		if(strcmp(pk->funcName,funcName) == 0){
			occ = pk->occurence;
			break;			
		}
		else{
			stackPop(symStack, (&pk));
			stackPush(backup, (&pk));
		}
	}
	while(!(stackIsEmpty(backup))){
		funcVars* b = (funcVars*) malloc (sizeof(funcVars));
		stackPop(backup, (&b));
		stackPush(symStack, (&b));
	}
	return occ;
}
Ejemplo n.º 4
0
void DFS_in_iterative(btree_node *root) {
    stack *s = createStack(20);
    btree_node *current = NULL;

    bTreeVisitedReset(root);

    if (s) {
        push(s, root);
        while (!stackIsEmpty(s)) {
            current = pop(s);
            if (!current->left || current->left->visited) {
                printf("%c ", current->key);
                current->visited = 1;
                if (current->right) { // it is not possible that the right child is visited
                    push(s, current->right);
                }
            } else {
                push(s, current);
                push(s, current->left);
            }
        }
        free(s);
    } else {
        fprintf(stderr, "Unable to create stack\n");
    }
}
char *reverseString(char *stringToReverse)
{
	int i, j = 0;
	char *reversedString;
	Stack *stack = stackNew(512);
	
	printf("stack:%p \n", stack);
	printf("size:%d, length:%d\n", stack->size, stack->length);
	
	for(i = 0; stringToReverse[i] != '\0'; i++)
	{
		stackPush(stack , (int)stringToReverse[i]);
		printf("%c", stringToReverse[i]);
	}
	
	printf("\ni:%d\n", i);
	reversedString = malloc(sizeof(char) * (i + 1));
	
	//while(i--)
	while(!stackIsEmpty(stack))
	{
		reversedString[j++] = stackPop(stack);
		printf("%c", reversedString[j-1]);
	}
	
	reversedString[j] = '\0';
	
	return reversedString;
}
Ejemplo n.º 6
0
btree_node * top(stack *s) {
    btree_node *r = NULL;
    if (!stackIsEmpty(s)) {
        r = s->els[s->top];
    }
    return r;
}
stackElement_t stackPop(stack_t *stackP)
{
	if (stackIsEmpty(stackP))
		exit(EXIT_FAILURE);

	return stackP->contents[stackP->top--];
}
Ejemplo n.º 8
0
uint16_t stackTop(stack *s) {
	if (!stackIsEmpty(s)) {
		return (*s).data;
	} else {
		return 0;
	}
}
Ejemplo n.º 9
0
// Returns 0 to indicate error
// Verify that the next stack element exists and is of the given type
// If e==ANY_TYPE, the type check is ommited 
static int checkPeek(Elm e) {
    if (stackIsEmpty(stack)){
        fprintf(stderr,"Illegal document structure, expected %s\n", elmNames[e]);
        XML_StopParser(parser, XML_FALSE);
        return 0; // error
    }
    return e==ANY_TYPE ? 1 : checkElementType(stackPeek(stack), e);
}
Ejemplo n.º 10
0
///////////////////////////////////////////////////////////////////////////////
/// Verify that the next stack element exists and is of the given type.
/// If e==ANY_TYPE, the type check is ommited. 
///
///\param e The element.
///\return 0 if there is no error occurred. Otherwise, return 1 to indicate an error.
///////////////////////////////////////////////////////////////////////////////
static int checkPeek(Elm e) {
    if (stackIsEmpty(stack)){
        printf("Illegal document structure, expected %s\n", elmNames[e]);
        XML_StopParser(parser, XML_FALSE);
        return 1; // error
    }
    return e==ANY_TYPE ? 0 : checkElementType(stackPeek(stack), e); //stackPeek() retrieves item at top of stack
}
Ejemplo n.º 11
0
Archivo: Stack.c Proyecto: zyb2013/ds
void *stackPeek(Stack *s)
{
	if (stackIsEmpty(s))
	{
		return NULL;
	}
	return s->head->data;
}
Ejemplo n.º 12
0
void stackDrop(stack **s) {
	stack *p;
	if (!stackIsEmpty((*s))) {
		p = (*s);
		(*s) = (*(*s)).next;
		free(p);
	}
}
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);
}
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;
}
Ejemplo n.º 15
0
Archivo: stack.c Proyecto: kinkemam/343
/* function that returns the top element in the stack without removing it */
stkElement stackPeek(stack *stkPtr)
{
	if (stackIsEmpty(stkPtr)) {
		fprintf(stderr, "Stack is empty - can't peek.\n");
		exit(1);
	}

	return (stkPtr->top)->element;
}
Ejemplo n.º 16
0
Archivo: minus.c Proyecto: vanjac/Minus
void halt()
{
  printf("Done.\n");
  int i;
  while(!stackIsEmpty())
    printf("%f\n", stackPop());
  closeAll();
  exit(0);
}
int stackFree(Stack *s)
{
    // Remove all elements from stack till it becomes empty.
    while(stackIsEmpty(s)==0)
                             stackPop(s);
    
    // Free memory used by stack.
    free(s);
}
Ejemplo n.º 18
0
int getExecutionFlag(){
    if(didFuncEntryExecute == NULL || stackIsEmpty(didFuncEntryExecute)){
        return 1;
    }
    else{
        int* execFlag = (int *)malloc(sizeof(int));
        stackPeek(didFuncEntryExecute,&execFlag);
        return *execFlag;
    }
}
Ejemplo n.º 19
0
uint16_t stackPop(stack **s) {
	uint16_t v;
	if (!stackIsEmpty((*s))) {
		v = stackTop((*s));
		stackDrop(s);
		return v;
	} else {
		return 0;
	}
}
Ejemplo n.º 20
0
void stackPop(Stack *s, void *element) {
  assert(!stackIsEmpty(s));
  node *top;
  top = s->head;
  s->head = s->head->next;    
  s->elementsCnt--;  
  memcpy(element, top->element, s->elementSize);
  free(top->element);
  free(top);
}
Ejemplo n.º 21
0
//////////////////////////////////////////////////////////////////////////////////
/// Parse the fmu. The receiver must call freeElement(md) to release AST memory.
///
///\param xmlPath The xml file to be parsed
///\return the root node md of the AST if no error occurred. NULL to indicate failure
/////////////////////////////////////////////////////////////////////////////////
ModelDescription* parse(const char* xmlPath) {
  ModelDescription* md = NULL;
  FILE *file;
  int done = 0;

  stack = stackNew(100, 10); // Allocate stack memory	  
  if (checkPointer(stack)) return NULL;  // Check if the stack is creatted

  parser = XML_ParserCreate(NULL); // Create an parser
  if (checkPointer(parser)) return NULL;  // Check if the parser is created

  XML_SetElementHandler(parser, startElement, endElement); // Set handler for start and end tags
  XML_SetCharacterDataHandler(parser, handleData); // Set handler for text

	file = fopen(xmlPath, "rb");

	if (file == NULL) {
    printfError("Cannot open file '%s'\n", xmlPath);
    XML_ParserFree(parser); // Free the memory for parser
    return NULL; // Failure
  }

  while (!done) {
    int n = fread(text, sizeof(char), XMLBUFSIZE, file); // Read XMLBUFSIZE characters from file
    if (n != XMLBUFSIZE) done = 1; // Reach the end of file
    if (!XML_Parse(parser, text, n, done)){
      printf("Parse error in file %s at line %d:\n%s\n",
             xmlPath,
             (int)XML_GetCurrentLineNumber(parser),
              XML_ErrorString(XML_GetErrorCode(parser)));
      while (!stackIsEmpty(stack)) md = stackPop(stack);
      if (md) freeElement(md);
      cleanup(file);
      return NULL; // failure
    }
  }

  md = stackPop(stack);
  assert(stackIsEmpty(stack));
  cleanup(file);
  //printElement(1, md); // Print the element for debugging
  return md; // Success if all refs are valid    
}
stackData * stackTop(Stack *s)
{
     // Return pointer to data at top of stack if stack is not empty.
     if(stackIsEmpty(s)==0)
                           return s->top->data;
     else
         printf("Error: Stack is empty.\n");
         
     return NULL;
}
Ejemplo n.º 23
0
CDGNode *pathToList(CDGNode * head) {
  assert(NULL != head);
  Stack *nodeStack = stackNew(sizeof(CDGNode *));
  CDGNode *node;
  CDGNode *list = NULL;
  postOrder(head, nodeStack);
  while (!stackIsEmpty(nodeStack)) {
    stackPop(nodeStack, &node);
    list = setNextNode(copyToPathNode(newBlankNode(), node), list);
  }
  return list;
}
Ejemplo n.º 24
0
int stackPop(stackT *stack, stackElementT *element)
{
    if(stackIsEmpty(stack)) {
        printf("stack is empty.\n");
        return -1;
    }

    *element = stack->contents[stack->top];
    stack->top--;

    return 0;
}
Ejemplo n.º 25
0
//pop
void* stackPop(struct stack *stack){
	void *data;
	pthread_mutex_lock(&stack->lock);	
	if(!stackIsEmpty(stack)){
		data = stack->row[stack->top];
		stack->top--;
		pthread_mutex_unlock(&stack->lock);
		return data;
	}
	pthread_mutex_unlock(&stack->lock);
	return NULL;
}
Ejemplo n.º 26
0
void deleteCDG(CDGNode * root) {
  if (NULL == root)
    return;
  CDGNode *node;
  Stack *nodeStack = stackNew(sizeof(CDGNode *));
  postOrder(root, nodeStack);
  while (!stackIsEmpty(nodeStack)) {
    stackPop(nodeStack, &node);
    deleteNode(node);
  }
  stackFree(nodeStack);
}
Ejemplo n.º 27
0
CDGNode *updateCDG(CDGNode * root, int initialize) {
  int size = sizeof(CDGNode *);

  assert(NULL != root);
  Stack *nodeStack = stackNew(size);
  CDGNode *node;
  postOrder(root, nodeStack);
  while (!stackIsEmpty(nodeStack)) {
    stackPop(nodeStack, &node);
    updateScore(node, initialize);
  }
  stackFree(nodeStack);
  return root;
}
Ejemplo n.º 28
0
void coverNodes(CDGNode * root, CDGNode * nodes[], int size) {
  assert(NULL != root);
  if (0 == size)
    return;
  Stack *nodeStack = stackNew(sizeof(CDGNode *));
  CDGNode *node;
  postOrder(root, nodeStack);
  while (!stackIsEmpty(nodeStack)) {
    stackPop(nodeStack, &node);
    visitIfExists(node, nodes, size);
  }
  updateCDG(root, 0);
  return;
}
Ejemplo n.º 29
0
Archivo: Stack.c Proyecto: zyb2013/ds
void *stackPop(Stack *s)
{
	int data;
	if (stackIsEmpty(s))
	{
		return NULL;
	}
	StackNode *oldHead = s->head;
	s->head = oldHead->next;
	data = oldHead->data;
	free(oldHead);
	s->size--;
	return data;
}
Ejemplo n.º 30
0
// Returns NULL to indicate failure
// Otherwise, return the root node md of the AST.
// The receiver must call freeElement(md) to release AST memory.
ModelDescription* parse(const char* xmlPath) {
    ModelDescription* md = NULL;
    FILE *file;
    int done = 0;
    stack = stackNew(100, 10);
    if (!checkPointer(stack)) return NULL;  // failure
    parser = XML_ParserCreate(NULL);
    if (!checkPointer(parser)) return NULL;  // failure
    XML_SetElementHandler(parser, startElement, endElement);
    XML_SetCharacterDataHandler(parser, handleData);
  	file = fopen(xmlPath, "rb");
	if (file == NULL) {
        fprintf(stderr,"Cannot open file '%s'\n", xmlPath);
     	XML_ParserFree(parser);
        return NULL; // failure
    }
    while (!done) {
        int n = fread(text, sizeof(char), XMLBUFSIZE, file);
	    if (n != XMLBUFSIZE) done = 1;
        if (!XML_Parse(parser, text, n, done)){
             fprintf(stderr,"Parse error in file %s at line %d:\n%s\n", 
                     xmlPath,
                         (int)XML_GetCurrentLineNumber(parser),
	                 XML_ErrorString(XML_GetErrorCode(parser)));
             while (! stackIsEmpty(stack)) md = stackPop(stack);
             if (md) freeElement(md);
             cleanup(file);
             return NULL; // failure
        }
    }
    md = stackPop(stack);
    assert(stackIsEmpty(stack));
    cleanup(file);
    //printElement(1, md); // debug
    return md; // success if all refs are valid    
}