Example #1
0
File: abp.c Project: pbmartins/AlgC
void ABPInOrderRep (PtABPNode proot)  /* travessia em in-ordem repetitiva - repetitive in-order traversal */
{
	PtABPNode Node = proot; PtStack Stack;

	if (proot == NULL) { Error = ABP_EMPTY; return;	} /* arvore vazia - empty tree */
	if ((Stack = StackCreate (sizeof (PtABPNode))) == NULL) { Error = NO_MEM ; return; }
	StackPush (Stack, &Node);	/* armazenar a raiz - storing the root */

	while (!StackIsEmpty (Stack))
	{
		if (Node != NULL)	/* não é um no externo - not an external node */
		{
			Node = Node->PtLeft;
			StackPush (Stack, &Node);	/* subarvore esquerda - left subtree */
		}
		else	/* é um no externo */
		{
			StackPop (Stack, &Node);	/* retirar e descartar o no externo - retrieve and ignore the external node */
			if (!StackIsEmpty (Stack))
			{
				StackPop (Stack, &Node);	/* recuperar o no anterior - retrieve and preview node */
				printf ("%d ", Node->Elem);	/* imprimir o elemento - printing the element */
				Node = Node->PtRight;	/* subarvore direita - right subtree */
				StackPush (Stack, &Node);
			}
		}
	}

	StackDestroy (&Stack);	/* destruir a pilha - releasing the stack */
    Error = OK;
}
bool check(int a[],int num){
	Stack text;
	InitializeStack(&text);
	Item temp;
	int read_edx= num;		//指示此时什么值应该被弹出 
	int arr_edx = num-1; 		//指示数组下标,数组反向读取 
	while(num--){
		if(StackIsFull(&text)){
			return false;
		}else{
			temp.data = a[arr_edx];
			Push(temp,&text);
			
			while(!(StackIsEmpty(&text)) && text.end->item.data == read_edx ){
				Pop(&text);
				read_edx--;
			}
		}
		arr_edx--;
	}
	
	if(StackIsEmpty(&text)){
		return true;
	}else{
		return false;
	}
}
int  dequeue (queue_t * queue,DATA_TYPE  * data){

	if( StackIsEmpty((queue->s1)) && StackIsEmpty((queue->s2)) )
	return 0;

	if(StackIsEmpty((queue->s2))){
		DATA_TYPE tempdata;
		while(stackPop((queue->s1),&tempdata))
			stackPush((queue->s2),tempdata);
	}

	stackPop((queue->s2),data);
	return 1;
}
Example #4
0
File: abp.c Project: pbmartins/AlgC
int ABPMultSum (PtABPNode proot, int pvalue)
{
    PtABPNode node = proot;
    PtStack stack;
    int sum = 0;

    if (proot == NULL) {
        Error = ABP_EMPTY;
        return -1;
    }

    if ((stack = StackCreate(sizeof(PtABPNode))) == NULL) {
        Error = NO_MEM;
        return -1;
    }

    StackPush(stack, &node);

    while (!StackIsEmpty(stack)) {
        StackPop(stack, &node);
        if (!(node->Elem % pvalue))
            sum += node->Elem;

        if (node->PtRight != NULL)
            StackPush(stack, &(node->PtRight));
        if (node->PtLeft != NULL)
            StackPush(stack, &(node->PtLeft));
    }

    StackDestroy(&stack);
    Error = OK;
    return sum;
}
Example #5
0
File: abp.c Project: pbmartins/AlgC
void ABPPostOrderRep (PtABPNode proot)  /* travessia em pós-ordem repetitiva - repetitive post-order traversal */
{
	PtABPNode Node = proot, Last = proot; PtStack Stack;

	if (proot == NULL) { Error = ABP_EMPTY; return;	}	/* arvore vazia - empty tree */
	if ((Stack = StackCreate (sizeof (PtABPNode))) == NULL) { Error = NO_MEM ; return; }

	while (1)	/* enquanto houver elementos para visitar - while there are nodes */
	{
			/* travessia pela esquerda até atingir a folha mais à esquerda - left traversal until the left most leaf */
		while (Node->PtLeft != NULL)
		{ StackPush (Stack, &Node); Node = Node->PtLeft; }

		/* se não tem subarvore direita ou já completou a sua travessia - without right subtree or already completed the traversal */
		while (Node->PtRight == NULL || Node->PtRight == Last)
		{
			printf ("%d ", Node->Elem);	/* imprimir o elemento - printing the element */
			Last = Node;	/* assinalar último elemento visitado - marking the last visited element */
					/* terminar quando não há mais elementos na pilha - terminate when there are no more elments in the stack */
			if (StackIsEmpty (Stack)) { StackDestroy (&Stack); Error = OK; return; }

			StackPop (Stack, &Node);	/* retirar o elemento anterior - retrieve the preview element */
		}

		StackPush (Stack, &Node);	/* recolocar o elemento na pilha - restore the element in the stack */
		Node = Node->PtRight;	/* iniciar travessia da subarvore direita - start the right subtree traversal */
	}
}
Example #6
0
int StackPeek(stackT stackP) {
  if (StackIsEmpty(stackP)) {
    fprintf(stderr, "Can't pop element from stack: stack is empty.\n");
    exit(1);  /* Exit, returning error code. */
  }
  return stackP->contents[stackP->top];
}
Example #7
0
File: abp.c Project: pbmartins/AlgC
unsigned int ABPSizeRep (PtABPNode proot)  /* cálculo do número de elementos repetitiva - repetitive number of nodes */
{
	PtABPNode Node = proot; PtStack Stack; unsigned int Number = 0;

	if (proot == NULL) { Error = ABP_EMPTY; return 0;	} /* arvore vazia - empty tree */

	if ((Stack = StackCreate (sizeof (PtABPNode))) == NULL) { Error = NO_MEM ; return 0; }
	StackPush (Stack, &Node);	/* armazenar a raiz - storing the root */

	while (!StackIsEmpty (Stack))	/* enquanto existirem nos - while there are nodes */
	{
		StackPop (Stack, &Node);	/* recuperar o no - retrieve the node */
		Number++;	/* contar o no - counting the node */

		/* armazenar a raiz da subarvore esquerda - storing the left subtree root */
		if (Node->PtLeft != NULL) StackPush (Stack, &Node->PtLeft);

		/* armazenar a raiz da subarvore direita - storing the right subtree root */
		if (Node->PtRight != NULL) StackPush (Stack, &Node->PtRight);
	}

	StackDestroy (&Stack);	/* destruir a pilha - releasing the stack */

    Error = OK;
	return Number;
}
Example #8
0
void qsort_1 (int *arr, int size) {
  stackT stack;
  stackElementT element, e;
  int k;
  StackInit (&stack, size);
  element.left = 0;
  element.right = size - 1;
  StackPush(&stack, element);
  while (!StackIsEmpty (&stack)) {
    element = StackPop (&stack);
    while (element.left < element.right) {
      if (element.right - element.left < SWITCH_THRESH) {
	insertsort(&arr[element.left], element.right - element.left + 1);
	element.left = element.right;
      } else {
	k = partition(arr, element.left, element.right);
	e.left = element.left;
	e.right = k;
	StackPush(&stack, e);
	element.left = k+1;
      }
    }
  }
  StackDestroy (&stack);
  return;
}
Example #9
0
void *qsort_4_thread (void *threadarg) {
  //global busy thread count mutex and cv
  static pthread_mutex_t mutex_busy = PTHREAD_MUTEX_INITIALIZER;
  static pthread_cond_t cv_work = PTHREAD_COND_INITIALIZER;
  //deference thread argument struct
  struct qsort_4_thread_args *args = threadarg;
  //working vars
  int left, right, idle = 1, pivot;
  stackElementT element;

  while (1) {
    while (idle) {
      //try to get work
      pthread_mutex_lock (&mutex_busy);
      if (!StackIsEmpty (args->work)) {
	element = StackPop (args->work);
	(*args->busy)++;
	pthread_mutex_unlock (&mutex_busy);
	left = element.left;
	right = element.right;
	idle = 0;
	continue;
      }
      //if there's no work and nobody is busy signal and quit
      if (*args->busy == 0) {
	pthread_cond_broadcast (&cv_work);
	pthread_mutex_unlock (&mutex_busy);
	return (void *) 0;
      }
      //wait for signal of more work
      pthread_cond_wait (&cv_work, &mutex_busy);
      pthread_mutex_unlock (&mutex_busy);
    }
    while (!idle) {
      //if nothing to do, set idle and decrement busy
      if (left >= right) {
	idle = 1;
	pthread_mutex_lock (&mutex_busy);
	(*args->busy)--;
	pthread_mutex_unlock (&mutex_busy);
	continue;
      }
      //if problem small enough, insert sort
      if (right - left < SWITCH_THRESH && left < right) {
	insertsort (&args->data[left], right - left + 1);
	left = right;
      } else {
	//else partition, push and signal
	pivot = partition (args->data, left, right);
	element.left = pivot + 1;
	element.right = right;
	right = pivot;
	pthread_mutex_lock (&mutex_busy);
	StackPush (args->work, element);
	pthread_cond_broadcast (&cv_work);
	pthread_mutex_unlock (&mutex_busy);
      }
    }
  }
}
int StackOrderIsLegal(StackElementType *input,StackElementType *output,int n){
	SeqStack S;
	StackElementType e;
	int i,j;
	i = j = 0;
	InitStack(&S);
	while(j<n){
		if(StackIsEmpty(&S)){
			Push(&S,input[i]);
			printf("Push%d\t",input[i]);
			i ++;
			continue;
		}
		GetTop(&S,&e);
		if(e == output[j]) {
			Pop(&S,&e);
			printf("Pop%d\t",e);
			i ++;
			j ++;
		}
		else if(i < n){
			Push(&S,input[i]);
			printf("Push%d\t",input[i]);
			i ++;
		}
		else {
			break;
		}
	
	}
	if(j < n) return 0;
	return 1;
}
bool Pop(Stack * pstack){
	if(StackIsEmpty(pstack)){
		return false;
	}
	
	if(pstack->size == 1){
		free(pstack->end);
		pstack->head = NULL;
		pstack->end  = NULL;	
	}
	else{
		int max_num = StackItemCount(pstack);
		Node * this_node;
		Node * pre_node = pstack->head;
		int count=1;
	
		while(count < max_num -1){
			pre_node = pre_node->next;
			count++;
		}
		
		this_node = pre_node->next;
		free(this_node);
		pre_node->next = NULL;
		pstack->end = pre_node;
	}

	pstack->size--;
	return true;
}
Example #12
0
stackElementT StackPop(stackT *stackP)
{
	if(StackIsEmpty(stackP))
	{
		fprintf(stderr, "Can't pop element from stack: stack is empty.\n");
		exit(1);	
	}
	return stackP->contents[stackP->top--];
}
Example #13
0
/**
 * @brief 
 * @param S 
 * @returns 
 * 
 * 
 */
ElementType StackTop(Stack S)
{
    if (!StackIsEmpty(S))
    {
	return S->next->element;
    }
    fprintf(stderr, "StackTop: empty stack");
    return 0;
}
Example #14
0
StackElement StackPop(stackT *stackP)
{
    if (StackIsEmpty(stackP)){
        fprintf(stderr, "Не могу вытолкнуть элемент: стек пуст");
        exit(1);
    }

    return stackP->contents[stackP->top--];
}
Example #15
0
bool isValid(char *s)
{
	int len = strlen(s);
	stackT left, right;
	StackInit(&left, len);
	StackInit(&right,len);
	int i;

	for(i = 0; i < len; i ++) 
	{
		StackPush(&left, s[i]);
	}
	char a, b;

	while(!StackIsEmpty(&left))
	{
		a = StackPop(&left);
		switch(a)
		{
			case '(':
				if(StackIsEmpty(&right)) return false;
				b = StackPop(&right);
				if( b != ')') return false;
				else break;
			case '[':
				if(StackIsEmpty(&right)) return false;
				b = StackPop(&right);
				if( b != ']') return false;
				else break;
			case '{':
				if(StackIsEmpty(&right)) return false;
				b = StackPop(&right);
				if( b != '}') return false;
				else break;
			case ')': StackPush(&right, a); break;
			case ']': StackPush(&right, a); break;
			case '}': StackPush(&right, a); break;
			default: printf("unrecognized char.\n");
		}
	}
	if(StackIsEmpty(&right)) return true;
	return false;
}
Example #16
0
stackElementT StackPop(stackT *stackptr)
{
  if (StackIsEmpty(stackptr)) 
  {
    fprintf(stderr, "Can't pop element from stack: stack is empty.\n");
    exit(1);  /* Exit, returning error code. */
  }

  return stackptr->contents[stackptr->top--];
}
Example #17
0
/**
 * @brief 
 * @param S 
 * @returns 
 * 
 * 
 */
ElementType StackPop(Stack S)
{
    if(StackIsEmpty(S))
    {
	fprintf(stderr, "StackPop: empty stack");
	exit(1);
    }
    PtrToStackNode first = S->next;
    S->next = first->next;
    first->next = NULL;
    return first->element;
}
Example #18
0
/**
 * @brief 
 * @param S 
 * 
 * 
 */
void StackMakeEmpty(Stack S)
{
    if (S == NULL)
    {
	fprintf(stderr, "Stack: Must use newStack first");
	exit(1);
    }
    while(!StackIsEmpty(S))
    {
	StackPop(S);
    }
}
Example #19
0
File: abp.c Project: pbmartins/AlgC
int ABPEvenOrderSum (PtABPNode proot)
{
    PtABPNode node = proot;
    PtStack stack;
    int order = 0, sum = 0;
    
    if (proot == NULL) {
        Error = ABP_EMPTY;
        return -1;
    }

    if ((stack = StackCreate(sizeof(PtABPNode))) == NULL) {
        Error = NO_MEM;
        return -1;
    }

    StackPush(stack, &node);

    while(!StackIsEmpty(stack)) {
        if (node != NULL) {
            node = node->PtLeft;
            StackPush(stack, &node);
        } else {
            StackPop(stack, &node);
            if (!StackIsEmpty(stack)) {
                StackPop(stack, &node);
                if (order++ & 1)
                    sum += node->Elem;
                node = node->PtRight;
                StackPush(stack, &node);
            }
        }
    }

    StackDestroy(&stack);
    Error = OK;
    return sum;
}
Example #20
0
File: abp.c Project: pbmartins/AlgC
void ABPPreOrderRep (PtABPNode proot)  /* travessia em pré-ordem repetitiva - repetitive pre-order traversal */
{
	PtABPNode Node = proot; PtStack Stack;

	if (proot == NULL) { Error = ABP_EMPTY; return;	} /* arvore vazia - empty tree */
	if ((Stack = StackCreate (sizeof (PtABPNode))) == NULL) { Error = NO_MEM ; return; }

	StackPush (Stack, &Node);	/* armazenar a raiz - storing the root */
	while (!StackIsEmpty (Stack))	/* enquanto existirem nos - while there are nodes */
	{
		StackPop (Stack, &Node);	/* recuperar o no - retrieve the node */
		printf ("%d ", Node->Elem);	/* imprimir o elemento - printing the element */

				/* colocar a raiz da subarvore direita, caso exista - storing the right subtree root if it exists */
		if (Node->PtRight != NULL) StackPush (Stack, &Node->PtRight);

				/* colocar a raiz da subarvore esquerda, caso exista - storing the left subtree root if it exists */
		if (Node->PtLeft != NULL) StackPush (Stack, &Node->PtLeft);
	}

	StackDestroy (&Stack);	/* destruir a pilha - releasing the stack */
    Error = OK;
}
Example #21
0
// This gets called in two circumstances.  It may be called for the roots
// in which case the stack will be empty and we want to process it completely
// or it is called for a constant address in which case it will have been
// called from RecursiveScan::ScanAddressesInObject and that can process
// any addresses.
PolyObject *RecursiveScan::ScanObjectAddress(PolyObject *obj)
{
    PolyWord pWord = obj;
    // Test to see if this needs to be scanned.
    // It may update the word.
    bool test = TestForScan(&pWord);
    obj = pWord.AsObjPtr();

    if (test)
    {
        MarkAsScanning(obj);
        if (obj->IsByteObject())
            Completed(obj); // Don't need to put it on the stack
        // If we already have something on the stack we must being called
        // recursively to process a constant in a code segment.  Just push
        // it on the stack and let the caller deal with it.
        else if (StackIsEmpty())
            RecursiveScan::ScanAddressesInObject(obj, obj->LengthWord());
        else
            PushToStack(obj);
    }

    return obj;
}
Example #22
0
// This is called via ScanAddressesInRegion to process the permanent mutables.  It is
// also called from ScanObjectAddress to process root addresses.
// It processes all the addresses reachable from the object.
void RecursiveScan::ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord)
{
    if (OBJ_IS_BYTE_OBJECT(lengthWord))
    {
        Completed(obj);
        return;
    }

    while (true)
    {
        ASSERT (OBJ_IS_LENGTH(lengthWord));

        // Get the length and base address.  N.B.  If this is a code segment
        // these will be side-effected by GetConstSegmentForCode.
        POLYUNSIGNED length = OBJ_OBJECT_LENGTH(lengthWord);
        PolyWord *baseAddr = (PolyWord*)obj;

        if (OBJ_IS_CODE_OBJECT(lengthWord))
        {
            // It's better to process the whole code object in one go.
            ScanAddress::ScanAddressesInObject(obj, lengthWord);
            length = 0; // Finished
        }
        ASSERT(! OBJ_IS_BYTE_OBJECT(lengthWord)); // Check - remove this later

        // else it's a normal object,

        // If there are only two addresses in this cell that need to be
        // followed we follow them immediately and treat this cell as done.
        // If there are more than two we push the address of this cell on
        // the stack, follow the first address and then rescan it.  That way
        // list cells are processed once only but we don't overflow the
        // stack by pushing all the addresses in a very large vector.
        PolyWord *endWord = baseAddr + length;
        PolyObject *firstWord = 0;
        PolyObject *secondWord = 0;

        while (baseAddr != endWord)
        {
            PolyWord wordAt = *baseAddr;

            if (wordAt.IsDataPtr() && wordAt != PolyWord::FromUnsigned(0))
            {
                // Normal address.  We can have words of all zeros at least in the
                // situation where we have a partially constructed code segment where
                // the constants at the end of the code have not yet been filled in.
                if (TestForScan(baseAddr)) // Test value at baseAddr (may side-effect it)
                {
                    PolyObject *wObj = (*baseAddr).AsObjPtr();
                    if (wObj->IsByteObject())
                    {
                        // Can do this now - don't need to push it
                        MarkAsScanning(wObj);
                        Completed(wObj);
                    }
                    else if (firstWord == 0)
                    {
                        firstWord = wObj;
                        // We mark the word immediately.  We can have
                        // two words in an object that are the same
                        // and we don't want to process it again.
                        MarkAsScanning(firstWord);
                    }
                    else if (secondWord == 0)
                        secondWord = wObj;
                    else break;  // More than two words.
                }
            }
            else if (wordAt.IsCodePtr())
            {
                // If we're processing the constant area of a code segment this could
                // be a code address.
                PolyObject *oldObject = ObjCodePtrToPtr(wordAt.AsCodePtr());
                // Calculate the byte offset of this value within the code object.
                POLYUNSIGNED offset = wordAt.AsCodePtr() - (byte*)oldObject;
                wordAt = oldObject;
                bool test = TestForScan(&wordAt);
                // TestForScan may side-effect the word.
                PolyObject *newObject = wordAt.AsObjPtr();
                wordAt = PolyWord::FromCodePtr((byte*)newObject + offset);
                if (wordAt != *baseAddr)
                    *baseAddr = wordAt;
                if (test)
                {
                    if (firstWord == 0)
                    {
                        firstWord = newObject;
                        MarkAsScanning(firstWord);
                    }
                    else if (secondWord == 0)
                        secondWord = newObject;
                    else break;
                }
            }
            baseAddr++;
        }

        if (baseAddr == endWord)
        {
            // We have done everything except possibly firstWord and secondWord.
            Completed(obj);
            if (secondWord != 0)
            {
                MarkAsScanning(secondWord);
                // Put this on the stack.  If this is a list node we will be
                // pushing the tail.
                PushToStack(secondWord);
            }
        }
        else // Put this back on the stack while we process the first word
            PushToStack(obj);

        if (firstWord != 0)
            // Process it immediately.
            obj = firstWord;
        else if (StackIsEmpty())
            return;
        else
            obj = PopFromStack();

        lengthWord = obj->LengthWord();
    }
}
Example #23
0
stackElementT StackTope(AbstractStack pila) {
	if (!StackIsEmpty(pila))
		return pila->datos[pila->cant - 1];
	else
		return NULL;
}
Example #24
0
stackElementT StackPop(AbstractStack pila) {
	if (!StackIsEmpty(pila))
		return pila->datos[--pila->cant];
	else
		return NULL;
}
Example #25
0
stackElementT Pop(stackADT stack) {
  if (StackIsEmpty(stack)) Error("Stos jest pusty");
  return stack->elements[--stack->count];
}
Example #26
0
stackElementT Pop(stackADT stack)
{
	if(StackIsEmpty(stack)) Error("Pop of an empty stack");
	return (stack->elements[--stack->count]);
}
int queueIsEmpty(queue_t * queue){
		
	StackIsEmpty((queue->s1));
	printf("queue empty\n" );
	return 1;
}
Example #28
0
void *qsort_3_thread (void *threadarg) {
  //global busy thread count mutex
  static pthread_mutex_t mutex_busy = PTHREAD_MUTEX_INITIALIZER;
  //deference thread argument struct
  struct qsort_3_args *args = threadarg;
  //working vars
  int left = 0, right = 0, idle = 1, pivot;
  stackElementT element;
  while (1) {
    if (right - left < SWITCH_THRESH && left < right) {
      //insertsort
#ifdef DEBUG
      printf("Performing insertsort on [%d,%d]\n", left, right);
#endif
      insertsort(&args->data[left], right - left + 1);
      left = right;
    }
    while (left >= right) {
      pthread_mutex_lock (&mutex_busy);
      if (!StackIsEmpty(args->work)) {
	if (idle) (*args->busy)++;
	idle = 0;
	element = StackPop (args->work);
	left = element.left;
	right = element.right;
#ifdef DEBUG
	printf("Thread accepted range [%d,%d]\nBusy threads: %d\n", left, right, *args->busy);
#endif
      } else {
	if (!idle) (*args->busy)--;
	idle = 1;
#ifdef DEBUG
	printf("Busy threads: %d\n", *args->busy);
#endif
      }
      pthread_mutex_unlock (&mutex_busy);
      if (right - left < SWITCH_THRESH && !idle) {
#ifdef DEBUG
	printf("Performing insertsort on [%d,%d]\n", left, right);
#endif
	insertsort(&args->data[left], right - left + 1);
	left = right;
      }
      if (*args->busy == 0) return (void *) 0;
    }
    //partition
    pivot = partition (args->data, left, right);
#ifdef DEBUG
    printf("Partitioned [%d,%d] found pivot %d\n", left, right, pivot);
#endif
    //push area to left
    element.left = left;
    element.right = pivot;
    pthread_mutex_lock (&mutex_busy);
#ifdef DEBUG
    printf("Pushing range [%d,%d]\n", element.left, element.right);
#endif
    StackPush (args->work, element);
    pthread_mutex_unlock (&mutex_busy);
    //process area to right
    left = pivot + 1;
  }
}
Example #29
0
stackElementT StackGetFirst(AbstractStack pila) {
	if (!StackIsEmpty(pila))
		return pila->datos[0];
	else
		return NULL;
}
Example #30
0
static void ClearStack(stackADT stack) 
{
  while (!StackIsEmpty(stack)) Pop(stack);
}