我想创建一个链接列表堆栈与流行和推送功能。 Push方法正在工作,但Pop不是。我无法弄清楚它的价值在哪里返回,我认为它应该在解决这个问题时起作用(对于可怜的措词抱歉)。链接列表堆栈弹出方法
这里是我的代码:
class Program
{
int nextFree;
int End;
int Start;
Names[] Stack;
Names greg = new Names();
Names matt = new Names();
Names jack = new Names();
Names fred = new Names();
public struct Names
{
public Int32 pointer;
public string data;
}
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 Program()
{
Stack = new Names[6];
greg.data = "Greg";
greg.pointer = 1;
matt.data = "Matt";
matt.pointer = 2;
jack.data = "Jack";
jack.pointer = 3;
fred.data = "Fred";
fred.pointer = -1;
Stack[0] = greg;
Stack[1] = matt;
Stack[2] = jack;
Stack[3] = fred;
nextFree = 4;
End = 5;
Start = 0;
}
public string Pop()
{
string value = string.Empty;
if (nextFree == -1)
{
Console.WriteLine("Stack is empty");
Console.ReadLine();
}
else
{
Names thisNode = Stack[End];
int temp = End;
End = thisNode.pointer;
thisNode.pointer = nextFree;
nextFree = temp;
}
this.ListAllNames();
return value;
}
public void Push()
{
if (nextFree >= Stack.Length)
{
Console.WriteLine("Stackoverflow, to many elements for the stack");
Console.ReadLine();
}
else
{
Console.WriteLine("Enter a name to be added");
string input = Console.ReadLine();
Stack[nextFree].data = input;
Stack[nextFree].pointer = End;
End = nextFree;
nextFree++;
}
this.ListAllNames();
}
public void ListAllNames()
{
foreach (Names name in Stack)
{
Console.WriteLine("Name:" + name.data);
}
}
}
}
家庭作业? (如果是这样,你可以做一些其他的事情来改善你的代码)。 – R0MANARMY
如果它应该是一个链表,为什么使用数组? –
@ R0MANARMY是的,我相信有很多事情,说实话,它没有那么好的编码:P。我只需要让Pop方法起作用,然后我就可以开始整理它,并且如果可以的话可以使它更有效率。 – user2852418