此功能“清除”链接列表中的重复项
def clean (self):
key_node = self._front
while key_node is not None:
# Loop through every node - compare each node with the rest
previous = key_node
current = key_node._next
while current is not None:
# Always search to the end of the list (may have > 1 duplicate)
if current._value == key_node._value:
# Remove the current node by connecting the node before it
# to the node after it.
previous._next = current._next
self._count -= 1
else:
previous = current
# Move to the _next node.
current = current._next
# Check for duplicates of the _next remaining node in the list
key_node = key_node._next
return
这个函数的递归方式如何?
答案 0 :(得分:0)
最简单的解决方案是将while循环转换为尾递归,但我猜这不是你想要的。
我认为_front和_count这个自我的东西是一个额外的结构" hold"列表 - 我们可以传递它(如下所示),或者之后重新计算列表成员。 它可能看起来像这样:
def clean(self)
self._front = rec_clean(self._front, self)
return
def rec_clean(current,self)
if current is None:
return None
else:
if member(current._value, current._next):
self._count -= 1
return rec_clean(current._next, self)
else:
current._next = rec_clean(current._next, self)
return current
def member(value, current)
if current is None:
return false
else:
if current._value == value
return true
else:
return member(value, current._next)
请注意,现在您只拥有每个值的最后一个(列出链接的列表),因此您可能希望之后反转列表。
重新计算新的"清理过的" list,你可以使用另一个递归函数:
def length(current)
if current is None:
return 0
else:
return 1+length(current._next)
祝你好运!
答案 1 :(得分:0)
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int number1,number2;
number1 = int.Parse(Console.ReadLine());
number2 = int.Parse(Console.ReadLine());
Console.WriteLine("the sum of numbers are " +" "+ (number1 + number2));
Console.ReadKey();
DoStuff(number1,number2);
}
public int DoStuff(int num1,int num2)
{
int result = num1 + num2;
return result;
}
}
}
只需调用self.clean_recursive()使其滚动,该参数仅用于递归。