/*************************************************************** * Que 7. Given an array A, the apan S[i] of A[i] is the * maximum number of consecutive elements A[j] * elements A[j] and such that A[j] <= A[i] * * Commenst : * * Parameters : integer arrays. * Retuns : longest spans * **************************************************************/ int *FindingSpans(int A[],int size) { LinkedListStack stack; int p; int * s = new int[size]; for(int i=0;i<size;i++) { while(!stack.IsEmpty()) { if(A[i] > A[stack.Top()]) stack.Pop(); else break; } if(stack.IsEmpty()) p = -1; else p = stack.Top(); s[i] = i-p; stack.Push(i); } return s; }
/************************************************************* * Que 5. Use stack to find minimum element for all stack * elements * * Comment : Creating min stack to get current index minimum * Element for all elements. * * 1. Improved space complexity by pushing in stack * Only if there is more less value available & * and popped only when the current stack top value * is equal to array value. * * Parameters : integer array * Retuns : None **************************************************************/ void GetMinimum(int A[],int size) { if(size == 0) return; LinkedListStack stack; stack.Push(A[0]); for(int i=1; i<size; i++) { if(stack.Top() > A[i]) stack.Push(A[i]); //else //stack.Push(stack.Top()); } for(int i=size - 1;i>=0;i--) printf("%d ",A[i]); printf("\n"); int c = stack.GetSize(); for(int i=0;i<c;i++) printf("%d ",stack.Pop()); printf("\n"); }
/******************************************************* * Que 2. Infix to Postfix conversion. * * Parameters : Expression * Retuns : None * * Time Complexity : O(N) *******************************************************/ char * InfixToPostFix(char A[]) { LinkedListStack stack; char * output = new char[1024]; int iOutput = 0; int tokenType = EMPTY; int i=0,num; char token; char topStack = '\0'; while((tokenType = ReadToken(A,i,token,num)) != EMPTY) { if(tokenType == OPERAND) //Numbers { //Add simply in output string output[iOutput++] = token; //num - '0'; } else if(tokenType == OPERATOR) //Mathematical operator { if(!stack.IsEmpty()) topStack = stack.Top(); else topStack = '\0'; if(topStack == '\0' || topStack == '(' || topStack == '{' || topStack == '[') { stack.Push(token); } else { if(CompairPrecedence(topStack,token)) stack.Push(token); else { while( topStack != -1 && !CompairPrecedence(topStack,token) && topStack != '\0' && topStack != '(' && topStack != '{' && topStack != '[') { output[iOutput++] = stack.Pop(); topStack = stack.Top(); } stack.Push(token); } } } else if(tokenType == RIGHTP) //Right parenthesis { char top = stack.Top(); while(top != '(' ) //&& topStack != '{' && topStack != '[') { output[iOutput++] = stack.Pop(); top = stack.Top(); } stack.Pop(); } else if(tokenType == LEFTP) //Left parenthesis { stack.Push(token); } } while(!stack.IsEmpty()) output[iOutput++] = stack.Pop(); output[iOutput] = '\0'; return output; }