Question

In: Computer Science

Consider an ADT with the same operators as a stack (push(), pop(), size(), empty()), except that...

  1. Consider an ADT with the same operators as a stack (push(), pop(), size(), empty()), except that the pop() operator returns the largest element rather than the element most recently pushed. For this to make sense, the objects on the stack must be totally ordered (e.g. numbers). Describe array and linked list implementations of the ADT. Your implementations should be as time and space efficient as you can manage. Give the running times for the CRUD operators.

Solutions

Expert Solution

Following solution are in c++.

Array based solution:-

'stack' array is used to store maximum element obtained so far. 'SIZE' denotes the maximum size of the stack. 'stack_itr' is used to iterate through the stack in LIFO(Last In First Out) order. Whenever any new element is added to the stack then it is compared with previous element is that exist and maximum among these two are inserted in the stack array. Also when we pop an element from the stack then it should n ot be considered afterwards.

#include <iostream>
using namespace std;
const int SIZE=5;
int stack[SIZE],stack_itr=0;

bool isEmpty()
{
   return (stack_itr==0);
}

int stack_size()
{
   return stack_itr;
}

void push(int x)
{
   if(stack_itr>=SIZE)
   {
       cout<<"Stack Overflow\n";
   }
   else
   {
       if(stack_itr==0)
           stack[stack_itr]=x;
       else
           stack[stack_itr]=max(stack[stack_itr-1],x);
       stack_itr++;
   }
}
void pop()
{
   // Before calling pop we should check whether stack is empty or not
   if(!isEmpty())
   {
       int x= stack[stack_itr-1];
       stack_itr--;
       cout<< x<<" ";
   }
   else
   {
       cout<<"Stack Underflow\n";
   }
}

int main() {
   push(1);
   push(3);
   push(2);
  
   //Size of the stack
   cout<<stack_size()<<"\n";
  
   // Largest element are printed in reverse order :
   pop();
   pop();
   push(5);
   pop();
   return 0;
}

Time complexity:

push(), pop(), stack_size() and  isEmpty() = O(1)

Space Complexity: = O(n)

Linked list based Implementation:

In this case, we for push operation we have to traverse the entire linked list as we only know the head pointer in linked list. Also when we reach the last node then we are inserting the maximum of current element and previous element.

For pop operation also we have to traverse the entire linked list and then print the last element and free the allocated memory.

#include <iostream>
using namespace std;
const int SIZE=5;
struct node
{
int data;
struct node *next;
};
int stack_itr=0;

bool isEmpty()
{
   return (stack_itr==0);
}

int stack_size()
{
   return stack_itr;
}

node * newNode(int x)
{
   node *tmp=new node();
   tmp->data=x;
   tmp->next=NULL;
   return tmp;
}
void push(int x,node **head)
{
   if(stack_itr>=SIZE)
   {
       cout<<"Stack Overflow\n";
   }
   else
   {
       if(stack_itr==0)
       {
           node *tmp=newNode(x);
           *head=tmp;
       }
       else
       {
           node *tmp=*head;
           while(tmp->next!=NULL)
               tmp=tmp->next;
           // we have store largest number upto that element
           tmp->next=newNode(max(x,tmp->data));
       }
       stack_itr++;
   }
}
void pop(node *head)
{
   // Before calling pop we should check whether stack is empty or not
   if(!isEmpty())
   {
       node *tmp=head;
       // Here there can be single node so checking tmp->next also
       while(tmp->next!=NULL && tmp->next->next!=NULL)
       {
           tmp=tmp->next;
       }
       int x;
       if(tmp->next==NULL)
       {
           x=tmp->data;
           free(tmp);
           head=NULL;
       }
       else
       {
           x=tmp->next->data;
           node *tmp2=tmp->next;
           tmp->next=NULL;
           free(tmp2);
       }
       stack_itr--;
       cout<< x<<" ";
   }
   else
   {
       cout<<"Stack Underflow\n";
   }
}

int main() {
   node * head =NULL;
  
   push(1,&head);
   push(3,&head);
   push(2,&head);
  
   //Size of the stack
   cout<<stack_size()<<"\n";
  
   // Largest element are printed in reverse order :
   pop(head);
   pop(head);
   push(5,&head);
   pop(head);
   return 0;
}

Time complexity:

push() and  pop() = O(n)

stack_size() and isEmpty() = O(1)

Space Complexity: = O(n)


Related Solutions

Reverse the contents of a stack using only stack operations [ push() and pop()  ]. Using the...
Reverse the contents of a stack using only stack operations [ push() and pop()  ]. Using the java and give the explanation
JAVA Stack - Implementation. You will be able to use the push, pop and peek of...
JAVA Stack - Implementation. You will be able to use the push, pop and peek of Stack concept. Post-Fix calculator - When an arithmetic expression is presented in the postfix form, you can use a stack to evaluate the expression to get the final value. For example: the expression 3 + 5 * 9 (which is in the usual infix form) can be written as 3 5 9 * + in the postfix. More interestingly, post form removes all parentheses...
Write a function that returns the largest value in a stack (only use push and pop)
Write a function that returns the largest value in a stack (only use push and pop)
# ArrayStack # TODO: push and pop using array stack with doubling technique. import numpy as...
# ArrayStack # TODO: push and pop using array stack with doubling technique. import numpy as np from future import print_function # Definisi class ArrayStack class ArrayStack(object): def __init__(self): self.data = np.zeros(20, dtype=np.int) self.count = 0 def isEmpty(self): pass # ubah saya def size(self): pass # ubah saya def push(self, obj): pass # ubah saya def pop(self): pass # ubah saya #-------------------------- # End of class if __name__ == "__main__": stack = ArrayStack() randn = np.random.permutation(1000) for i in range(1000):...
3.1 Implement the stack ADT using array (4 marks) 3.1.1 Implement the pop() operation in the...
3.1 Implement the stack ADT using array 3.1.1 Implement the pop() operation in the stack (1 mark) Implement a stack class named Stack2540Array using array. The starter code is as follows. The instance variables and most operations are provided. You need to implement the pop operation. Make sure that your program checks whether the stack is empty in the pop operation. import java . io .*; import java . util .*; public class Stack2540Array { int CAPACITY = 128; int...
All code should be in Python 3. Implement the Stack Class, using the push, pop, str,...
All code should be in Python 3. Implement the Stack Class, using the push, pop, str, init methods, and the insurance variable 'list'.
Please code in C /* Implements functions that operate on Stack 1. PUSH 2. POP 3....
Please code in C /* Implements functions that operate on Stack 1. PUSH 2. POP 3. isEmpty 4. PEEK 5. Size */ #include <stdio.h> #define CAPACITY 1000 //Two stacks .. for each stack we need // 1. An Array that can hold capacity of elements // 2. A top initialzied to -1 (signifying that the stak is empty at the start) //NOTE : THESE STACKS ARE OF TYPE CHAR :( ... so you need to FIX IT!!!! to int and...
(In Java) Design a stack that supports getMin(), pop() and push() in O(1) time. Must use...
(In Java) Design a stack that supports getMin(), pop() and push() in O(1) time. Must use the iterator and comparator, does not need to be a linked list, although it's what I've tried using. I'm using another tester class to test this class. import java.util.Comparator; import java.util.List; import java.util.LinkedList; import java.util.Iterator; import java.util.Stack; import java.util.ListIterator; public class FMinStack<T> implements MinStack<T> { protected Comparator<? super T> comp; T min; protected List<T> ds; public FMinStack() { this(new DefaultComparator<T>()); } public FMinStack(Comparator<? super...
5 marks] A MinStack supports three main operations: the standard Stack operations push(x) and pop() and...
5 marks] A MinStack supports three main operations: the standard Stack operations push(x) and pop() and the non-standard min() operation which returns the minimum value stored on the stack. The zip file gives an implementation SlowMinStack that implements these operations so that push(x) and pop() each run in O(1) time, but  min()runs in Θ(n) time. For this question, you should complete the implementation of FastMinStack that implements all three operations in O(1) time per operation. As part of your implementation, you...
Suppose an initially empty stack S has performed a total of 15 push operations, 12 top...
Suppose an initially empty stack S has performed a total of 15 push operations, 12 top operations, and 13 pop operations ( 3 of which returned null to indicate an empty stack ). What is the current size of S? Question 1 options: Question 2 (1 point) Saved What values are returned during the following series of stack operations, if executed upon an initially empty stack? push(5), push(3), pop(), push(2), push(8), pop(), pop(), push(9), push(1), pop(), push(7), push(6), pop(), pop(),...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT