I am writing a method that takes in an integer "nth" that operates on a linked list of generics and returns every nth element. If the list is 0-99 and nth is 10, it should return a list of 0, 10, 20, 30, 40, 50, 60, 70, 80, 90. If the list is "a", "b", "c", "d", and nth is 4, it should return "d".
我正在编写一个方法,它接受一个整数“nth”,该整数对泛型链表进行操作,并每隔n个元素返回一次。如果列表是0-99,第n个是10,它应该返回一个0、10、20、30、40、50、60、70、80、90的列表。如果列表是“a”、“b”、“c”、“d”,并且第n个是4,则它应该返回“d”。
I am using C#.
我正在使用C#。
public OurList<T> SkipList(int nth)
{
if (nth <= 0)
throw new ArgumentOutOfRangeException("Nth must be positive");
OurList<T> newList = new OurList<T>();
Node pTmp = first;
int count = 0;
while (pTmp != null)
{
if ((count % nth) == 0)
newList.AddLast(pTmp.Data);
pTmp = pTmp.Next;
count++;
}
return newList;
}
This is what I have so far, and it works but not for both cases described above. If I initialize my count variable at 0, it works for the 0-99 list, but returns "a" instead of "d" for the letters. If I initialize my count variable at 1 it works for the list of letters. I can't seem to figure out a way to get it work for both lists.
这就是我到目前为止所拥有的,它是有效的,但不适用于上述两种情况。如果我将count变量初始化为0,则它适用于0-99列表,但返回字母“a”而不是“d”。如果我将count变量初始化为1,则它适用于字母列表。我似乎想不出一种方法让它同时适用于这两份清单。
Any advice would be helpful.
任何建议都会有所帮助。
更多回答
Your expected results are inconsistent. For the list of numbers, you’re accepting 0 * nth
and 1 * nth
, but for the list of letters you want 1 * (nth - 1)
(d
is at index 3). The results you’re getting are correct for your problem description (a
is at index 0 which is 0 * nth
).
您的预期结果不一致。对于数字列表,您接受0*n和1*n,但对于字母列表,您需要1*(nth-1)(d位于索引3)。您得到的结果对于您的问题描述是正确的(a位于索引0,即0*n)。
What is OurList<T>
, please?
请问我们的名单是什么?
OurList<T> is the return type of the method. It's a linked list implementation.
OurList是方法的返回类型。这是一个链表实现。
why would you accept the first element in a lists of integers but not in a lisst of strings?
为什么要接受整数列表中的第一个元素,而不接受字符串列表中的第一个元素呢?
I'm not accepting any values from the list. Nth is the number that is used to iterate by, essentially. Count is a variable used to keep track of nodes with in the list.
我不接受列表中的任何值。本质上,第n个数字是用于迭代的数字。Count是一个变量,用于跟踪列表中的节点。
我是一名优秀的程序员,十分优秀!