C# 通过列表代码检查堆栈实现,我的解决方案正确吗?
我的编程课有作业要做,我不知道我的解决方案对吗? 我必须按列表实现堆栈,但我不知道我是否正确理解了它 对不起,我的英语:)C# 通过列表代码检查堆栈实现,我的解决方案正确吗?,c#,C#,我的编程课有作业要做,我不知道我的解决方案对吗? 我必须按列表实现堆栈,但我不知道我是否正确理解了它 对不起,我的英语:) 看起来,您正试图通过(众所周知的经典问题)实现堆栈,而不是;如果您坚持列表 代码将非常简单。您的代码已重写到列表: //-让我们有一个通用堆栈,例如MyStack或MyStack 公共类MyStack{ //存储堆栈项的列表 私有列表m_项=新列表(); //没什么好写的,我们可以安全地放弃这个构造函数 公共MyStack(){} 公共无效推送(T项){ //只需将项目添加
看起来,您正试图通过(众所周知的经典问题)实现
堆栈,而不是;如果您坚持列表
代码将非常简单。您的代码已重写到列表
:
//-让我们有一个通用堆栈,例如MyStack或MyStack
公共类MyStack{
//存储堆栈项的列表
私有列表m_项=新列表();
//没什么好写的,我们可以安全地放弃这个构造函数
公共MyStack(){}
公共无效推送(T项){
//只需将项目添加到项目中
m_项目。添加(项目);
}
公共广播电台{
//我们无法从空堆栈中弹出项目
如果(m_Items.Count=0;--i)
控制台写入线(m_项[i]);
}
}
事实上,你应该告诉我们什么不起作用,如果一切都起作用,你会去代码审查网站进行验证。不过,我可以在Print()
中发现一个问题:它会使堆栈无效-请尝试连续调用它两次。看起来,您试图通过链表实现stack
,而不是list@DmitryBychenko那么通过列表它应该是什么样子呢?你能解释一下吗?:)您需要一个指针,它是指向顶部元素的索引,push将使用add方法,而pop将使用removeat方法fromList@Daras:List
(用C#表示),例如List
是一个类似数组的集合,您可以在其中添加
项,也可以删除
(删除
)项。
using System;
using System.Collections.Generic;
using System.Text;
namespace Zad._20
{
class Element
{
public String value;
public Element previous;
public Element(String value) {
this.value = value;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Zad._20
{
class Stack
{
private Element top;
public Stack() {
top = null;
}
public void Push(Element e) {
e.previous = top;
top = e;
}
public void Pop() {
top = top.previous;
}
public void Print() {
while(top != null) {
Console.WriteLine(top.value);
top = top.previous;
}
}
}
}
// <T> - let's have a generic stack, e.g. MyStack<int> or MyStack<String>
public class MyStack<T> {
// List<T> in which we store the stack's items
private List<T> m_Items = new List<T>();
// Nothing to write home about; we can safely drop this constructor
public MyStack() {}
public void Push(T item) {
// Just add item to the items
m_Items.Add(item);
}
public T Pop() {
// We can't Pop an item from the empty stack
if (m_Items.Count <= 0)
throw new InvalidOperationException("Stack is empty");
else {
// Take the last item
T result = m_Items[m_Items.Count - 1];
// Remove it (the last item) from the list
m_Items.RemoveAt(m_Items.Count - 1);
// Return the last item
return result;
}
}
public void Print() {
// Print out all the items in reversed order
for (int i = m_Items.Count - 1; i >= 0; --i)
Console.WriteLine(m_Items[i]);
}
}