我有一些迭代方法,添加,刪除,按索引搜索,並計算我的鏈表上的具體名稱,但我想實現它們使用遞歸解決方案。如何將迭代函數轉換爲遞歸函數?
我不確定如何開始。爲了進行轉換,我是否應該遵循任何準則?
這裏是我的代碼:
在LinkedList的方法來計算具體的名稱
public int CountName(string name)
{
int count = 0;
for (Node current = firstNode; current != null; current = current.Next)
{
count++;
if (current.patient.Name == name) return count;
}
return 0;
}
GET節點方法
public Node GetNode(string name)
{
for (Node current = firstNode; current != null; current = current.Next)
{
if (current.patient.Name == name)
{
return current;
}
}
return null;
}
刪除方法
public void Delete(string name)
{
Node last = lastNode;
if (last.patient.Name == name)
{
firstNode = firstNode.Next;
}
else if (lastNode.patient.Name == name)
{
Node temp = firstNode;
while (temp.Next != lastNode)
{
temp = temp.Next;
}
lastNode = temp;
temp.Next = null;
}
else
{
for (Node current = firstNode; current != null; current = current.Next)
{
if (current.patient.Name == name)
{
last.Next = current.Next;
}
else
{
last = current;
}
}
size--;
}
}
打印所有什麼在我的鏈表法
public List<string> PrintAll()
{
List<String> temp = new List<string>();
if (firstNode == null)
{
temp.Add("There are no items in the linked list");
return temp;
}
else
{
Node helpNode = firstNode;
while (helpNode != null)
{
temp.Add(helpNode.GetPatient().Name);
helpNode = helpNode.getNext();
}
return temp;
}
}
因爲SO不是代碼編寫服務 – Arion
您的'CountName'方法不會返回具有指定名稱的節點的計數(這聽起來像是它應該做的),而是返回節點直到幷包含具有指定名稱的* first *節點。這是意圖嗎? –
歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [在主題](http://stackoverflow.com/help/on-topic)和[如何提問](http://stackoverflow.com/help/how-to-ask)適用於此處。 StackOverflow不是一個設計,編碼,研究或教程服務。 互聯網上有許多教程和其他網站,涉及迭代和遞歸之間的轉換,以及許多關於堆棧溢出的早期問題。在發佈「新」問題之前,您需要使用這些*。 – Prune