Pages

Search

Thursday, October 9, 2008

Building Stack with Console

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{


using System;
class Node
{
public Node objNode;
public Object objObject;
public Node(Node argNode, Object argObj)
{
objNode = argNode;
objObject = argObj;
}

}
class ExStack
{

Node objNode = null;
public void Push(Object argObject)
{
objNode = new Node(objNode, argObject);
}
private bool IsNumber(string strValue)
{
try
{
int.Parse(strValue);
return true;
}
catch (Exception exp)
{
return false;
}
}
public Object this[int Index]
{
set
{
Node objInnNode = GetNode(Index);
if (objInnNode != null)
{
objInnNode.objObject=value;
}
}
get
{
Node objInnNode=GetNode(Index);
if (objInnNode != null)
{
return objInnNode.objObject;
}
return null;
}
}

public Node GetNode(int intIndex)
{
Node objInnerNode = objNode;
while (objInnerNode != null)
{
if (intIndex == 0)
return objInnerNode;
else
{
objInnerNode = objInnerNode.objNode;
intIndex--;
}
}
return null;
}
public Object Pop()
{
if (objNode != null)
{
Object objVal = objNode.objObject;
objNode = objNode.objNode;
return objVal;

}
return null;
}


class Test
{

static void Main()
{
ExStack objLclExStack = new ExStack();

while (true)
{
Console.WriteLine("Enter Some Value");
Console.WriteLine(" 1 to view details\n 2 to Exit\n3 to Pop\n 4 to access with Index \nOther Value to Push");
string strValue = Console.ReadLine();
if (strValue == "1")
{
if (objLclExStack != null)
{
Node objLclNode = objLclExStack.objNode;
while (objLclNode != null)
{
if (objLclNode != null)
{
Console.Write(objLclNode.objObject.ToString() + " -- >");
}
else
{
break;
}
objLclNode = objLclNode.objNode;
}
}
Console.WriteLine(" ");
}
else if (strValue == "2")
{
break;
}
else if (strValue == "3")
{
Object obj = objLclExStack.Pop();
if (obj != null)
{
Console.WriteLine(obj.ToString());
}
else
{
Console.WriteLine("No Elemnts To Pop");
}
}
else if (strValue == "4")
{
Console.WriteLine(" Enter Index To View");
strValue = Console.ReadLine();
while (!objLclExStack.IsNumber(strValue))
{
Console.WriteLine("Please Enter valid Index To View");
strValue = Console.ReadLine();
}
Object objValue= objLclExStack[int.Parse(strValue)];

if (objValue != null)
{
Console.WriteLine("Value at Index " + strValue + " is " + objValue.ToString());
Console.WriteLine("Do you like to edit Y or N");
string strNewValue = Console.ReadLine();
if (strNewValue == "Y")
{
Console.WriteLine("Please Enter Value");
strNewValue = Console.ReadLine();
objLclExStack[int.Parse(strValue)] = (Object)strNewValue;
}
}
else
{
Console.WriteLine("Index " + strValue + " does not exist");
}
}
else
{
objLclExStack.Push((Object)strValue);
}
}
}
}
}
}

No comments:

Post a Comment