我想讓我的推送和流行方法工作,但似乎無法做到。通過Push方法,我認爲這與nextfree有關,但我不確定。另外用Pop方法我不確定如何去做,我會在我的實際代碼下面放置僞代碼。 這裏是我的代碼:堆棧推送和流行
class Program
{
private string[] Stack = new string[5];
int nextFree = 3;
public Program()
{
Stack = new string[5];
Stack[0] = "Greg";
Stack[1] = "Matt";
Stack[2] = "Jack";
Stack[3] = "Fred";
}
static void Main(string[] args)
{
Program prog = new Program();
do
{
prog.DisplayMenu();
}
while (true);
}
public void DisplayMenu()
{
Int32 userInput = 0;
Console.WriteLine("Linear Stack");
Console.WriteLine("1: Add to stack");
Console.WriteLine("2: Delete from stack");
userInput = Int32.Parse(Console.ReadLine());
switch (userInput)
{
case 1:
this.Push();
break;
case 2:
this.Pop();
break;
}
}
public void Push()
{
if (nextFree == Stack.Length)
{
Console.WriteLine("Stackoverflow, to many elements for the stack");
Console.ReadLine();
}
else
{
Console.WriteLine("Please enter a name to be added");
string userInput = Console.ReadLine();
nextFree++;
Stack[nextFree] = userInput;
}
this.list();
}
public void Pop()
{
if (nextFree == -1)
{
Console.WriteLine("Stack is empty");
Console.ReadLine();
}
else
{
nextFree--;
}
this.list();
}
public void list()
{
foreach (string s in Stack)
{
Console.Write(s + " ");
}
Console.WriteLine();
}
}
}
流行的僞代碼:
If Stack is empty
Then error
Else
Return Stack[TopOfStackPointer]
Decrement TopOfStackPointer
EndIF
UPDATE: 現在的Push方法的工作原理與nextFree正與值3
沒有錯誤的描述,它幾乎不可能幫助你。 –
@ Dan-o推送方法沒有錯誤,只是在我使用它的時候,添加的任何名字都會替換已經在堆棧中的名字。另外對於Pop方法,即使使用提供的僞代碼,我也不確定如何操作。 – user2852418