gpt4 book ai didi

c# - 堆栈推送和弹出

转载 作者:行者123 更新时间:2023-11-30 13:46:35 25 4
gpt4 key购买 nike

我正在尝试让我的 push 和 pop 方法工作,但似乎做不到。对于 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

更新:Push 方法现在可以使用值 3 启动的 nextFree。

最佳答案

您需要在第一次启动时将 nextFree 的值实例化为 4(因为您的堆栈中已经有 4 个项目)。

当检查 nextFree 的值是否超出 not 的范围时,您需要记住数组索引是从零开始的(即它们从 0 开始)。所以你的条件应该是:

if(nextFree >= Stack.Length - 1)

关于c# - 堆栈推送和弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com