我想让我的推送和流行方法工作,但似乎无法做到。通过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