using System;
namespace C5_6_1
{
///
///用陣列實作出堆疊和出堆疊操作
///
public class Stack
{
// static void Main() { }
private const int stackMaxLength = 100;
//定義字元陣列,用於儲存堆疊的資料
char[] strStack = new char[stackMaxLength];
//定義堆疊頂指針
public int currentPos;
///
///建構子
///
public Stack()
{
currentPos = 0; //清空堆疊
}
///
///入堆疊操作
///
///入堆疊的字串
///
public bool Push(char str)
{
//防止堆疊滿
if (currentPos >= stackMaxLength)
{
return false;
}
//把數據入堆疊
strStack[currentPos] = str;
currentPos++;
return true;
}
///
///出堆疊操作
///
///
public char Pop()
{
//防止堆疊空
if (currentPos <= 0)
{
return '\0';
}
//出堆疊
currentPos--;
return strStack[currentPos];
}
}
}
//執行堆疊操作
using System;
namespace C5_6_1
{
public class Test
{
public static void Main()
{
string test = null;
int i;
//宣告一個推疊物件
Stack stack = new Stack();
Console.WriteLine("請輸入你要測試的字串:");
test = Console.ReadLine();
//將輸入的字串依次入堆疊
for (i = 0; i < test.Length; i++)
{
stack.Push(test[i]);
}
//按先進後出的原則出堆疊,並列印出來
Console.WriteLine("輸入字串的反序為:");
for (i = 0; i < test.Length; i++)
{
Console.Write(stack.Pop());
}
}
}
}
沒有留言:
張貼留言