Getmin() operation of stack in O(1) complexity.
public class Stacks :stack
{
stack minstack, normalstack;
public Stacks(int size)
{
minstack = new stack(1);
normalstack = new stack(size);
}
public void Push(int item)
{
if (normalstack.isEmpty())
{
normalstack.push(item);
minstack.push(item);
}
else
{
normalstack.push(item);
int y = minstack.pop();
if (item < y)
minstack.push(item);
else
minstack.push(y);
}
}
public int minvalue()
{
return minstack.pop();
}
}
public class stack
{
int[] a;
int top;
int _size;
public stack()
{
}
public stack(int size)
{
a = new int[size];
top = -1;
_size = size;
}
public bool isEmpty()
{
if (top == -1)
return true;
else
return false;
}
public bool isFull()
{
if (top == _size - 1)
return true;
else
return false;
}
public void push(int x)
{
if (isFull())
Console.WriteLine("stack is full");
else
{
a[++top] = x;
}
}
public int pop()
{
int x=Int32.MinValue;
if (isEmpty())
Console.WriteLine("stack is empty");
else
x = a[top--];
return x;
}
}
public class Stacks :stack
{
stack minstack, normalstack;
public Stacks(int size)
{
minstack = new stack(1);
normalstack = new stack(size);
}
public void Push(int item)
{
if (normalstack.isEmpty())
{
normalstack.push(item);
minstack.push(item);
}
else
{
normalstack.push(item);
int y = minstack.pop();
if (item < y)
minstack.push(item);
else
minstack.push(y);
}
}
public int minvalue()
{
return minstack.pop();
}
}
public class stack
{
int[] a;
int top;
int _size;
public stack()
{
}
public stack(int size)
{
a = new int[size];
top = -1;
_size = size;
}
public bool isEmpty()
{
if (top == -1)
return true;
else
return false;
}
public bool isFull()
{
if (top == _size - 1)
return true;
else
return false;
}
public void push(int x)
{
if (isFull())
Console.WriteLine("stack is full");
else
{
a[++top] = x;
}
}
public int pop()
{
int x=Int32.MinValue;
if (isEmpty())
Console.WriteLine("stack is empty");
else
x = a[top--];
return x;
}
}
No comments:
Post a Comment