CSharp · Console
// Implement 2 stacks of integers on the base of integer array of fixed size. The total
// length of both stacks can be limited by the size of the array (e.g. it is OK to crash on
// attempt to push too many elements in total).
using System;
public class TwoStacks
{
// stack 1 occupies first count1 elements of array with the bottom at data[0]
// stack 2 occupies last count2 elements of array with the bottom at data[data.Length-1]
int count1, count2;
int[] data;
public TwoStacks(int n)
{
data = new int[n];
count1 = 0;
count2 = 0;
}
public void Push1(int v)
{
AssertNotFull();
data[count1] = v;
count1++;
}
public void Push2(int v)
{
AssertNotFull();
count2++;
data[data.Length - count2] = v;
}
public int Pop1()
{
if (count1 <= 0)
throw new ApplicationException("Stack1 underflow");
count1--;
return data[count1];
}
public int Pop2()
{
if (count2 <= 0)
throw new ApplicationException("Stack2 underflow");
int v = data[data.Length - count2];
count2--;
return v;
}
private void AssertNotFull()
{
if (count1 + count2 >= data.Length)
throw new ApplicationException("Container is full");
}
}
public class Program
{
public static void Main(string[] args)
{
TwoStacks s = new TwoStacks(5);
TestPush(s, 1, 5);
TestPush(s, 2, 100);
TestPush(s, 2, 67);
TestPush(s, 1, 89);
TestPush(s, 2, 9);
TestPop (s, 1);
TestPush(s, 2, 40);
TestPop (s, 2);
}
private static void TestPush(TwoStacks s, int index, int v)
{
Console.WriteLine("Push{0}({1})", index, v);
if(index==1)
s.Push1(v);
else if(index==2)
s.Push2(v);
}
private static void TestPop(TwoStacks s, int index)
{
int v = -1;
if(index==1)
v = s.Pop1();
else if(index==2)
v = s.Pop2();
Console.WriteLine("Pop{0} = {1}", index, v);
}
}