【发布时间】:2021-07-31 02:06:49
【问题描述】:
我需要检查堆栈中是否有重复项(仅在基本方法 pop、push、top、isempty 中使用) 如果堆栈没有重复,则返回 true;如果堆栈为空,则返回 true 如果堆栈有重复则返回 false
public static bool CheckStack(Stack<int> s, int x)
{
Stack<int> s1 = new Stack<int>();
bool flag = false;
if (s.IsEmpty())
return false;
while (!s.IsEmpty() && ! flag)
{
int temp = s.Pop();
s1.Push(temp);
if (temp == x)
flag = true;
}
s = s1;
return flag;
}
public static bool SpecialStack(Stack<int> s)
{
int temp = s.Pop();
while(!s.IsEmpty() && !CheckStack(s,temp))
{
temp = s.Pop();
}
if (s.IsEmpty())
return true;
return false;
}
public static void Main()
{
Stack<int> st3 = new Stack<int>();
st3.Push(7);
st3.Push(2);
st3.Push(1);
st3.Push(8);
st3.Push(7);
Console.WriteLine(SpecialStack(st3));
}
如何在不使用其他函数的情况下做到这一点,以及解决方案需要使用基本方法而不使用 c# 的内置函数的最短方法
【问题讨论】:
-
由于这不是关于特定的编程问题,我认为Code Review可能会更好
-
这能回答你的问题吗? C# LINQ find duplicates in List
标签: c# duplicates stack