你是不是打错字了,那个数组一共就5个长度,怎么来的stack[9]。我想应该这么说:
有两个栈s1和s2共享同一数组存储空间stack[N],其中栈s1的栈底设在stack[0]处,而栈s2的栈底设在stack[9]处,请编写栈s1和s2的进栈操作push(i,x)和退栈操作pop(i),其中i=1、2,分别表示栈s1和s2
这样一来就清晰了
恩,应该是吧,不过我还是不会代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyStack { class Program { static void Main(string[] args) { MyStack<String> testStack = new MyStack<String>(14); testStack.Push(1, "有森玲香"); testStack.Push(1, "雨宫优衣"); testStack.Push(1, "原千寻"); testStack.Push(1, "原史奈"); testStack.Push(1, "原田春奈"); testStack.Push(1, "远野麻耶"); testStack.Push(1, "月野静玖"); testStack.Push(1, "早纪麻未"); testStack.Push(2, "樱桃小丸子"); testStack.Push(2, "工藤新一"); testStack.Push(2, "怪盗基德"); testStack.Push(2, "三井寿"); testStack.Push(2, "皮卡丘"); Console.WriteLine(testStack.Pop(1)); Console.WriteLine(testStack.Pop(1)); Console.WriteLine(testStack.Pop(1)); Console.WriteLine(testStack.Pop(1)); Console.WriteLine(testStack.Pop(1)); Console.WriteLine(testStack.Pop(1)); Console.WriteLine(testStack.Pop(1)); Console.WriteLine(testStack.Pop(1)); Console.WriteLine(testStack.Pop(2)); Console.WriteLine(testStack.Pop(2)); Console.WriteLine(testStack.Pop(2)); Console.WriteLine(testStack.Pop(2)); Console.WriteLine(testStack.Pop(2)); Console.ReadLine(); } } class MyStack<T> { private int _length; private int _s1Index = 0 - 1; private int _s2Index = 9 - 1; private T[] _stack; public MyStack(int length) { if (length < 9) { throw new Exception("are you joke?"); } _length = length; _stack = new T[_length]; } public T Pop(int i) { if (i != 1 && i != 2) { throw new Exception("什么玩意儿?"); } if (i == 1) { if (_s1Index >= 0) { return _stack[_s1Index--]; } else { throw new Exception("there is no shit anymore"); } } else { if (_s2Index >= 9) { return _stack[_s2Index--]; } else { throw new Exception("there is no shit anymore"); } } } public void Push(int i, T t) { if (i != 1 && i != 2) { throw new Exception("什么玩意儿?"); } if (i == 1) { int insertIndex = _s1Index + 1; if (insertIndex < 9) { _stack[insertIndex] = t; _s1Index += 1; } else { throw new Exception("不好意思,客满"); } } else { int insertIndex = _s2Index + 1; if (insertIndex < _length) { _stack[insertIndex] = t; _s2Index += 1; } else { throw new Exception("不好意思,客满"); } } } } }
@会长: 嗯,谢谢啦
@于雨忆女: 程序运行不出来结果呀,总有错误。。。恳请高手在改改
@于雨忆女: 我这里可以啊,有什么错误。另外你改改里面的提示语,我瞎写的