谁能告诉我如何从特定位置插入或删除节点。请用示例代码解释它,以便我能很好地理解它。谢谢
问问题
2531 次
1 回答
2
这个想法是:
1°/ 找到要插入或删除的位置。
2°/ 保存下一个节点以将其链接到新节点(插入)或前一个节点(删除)
插入应该是这样的:
public class Node
{
public string Name { get; set; }
public Node Next { get; set; }
public void InsertAt(string name, int index, Node start)
{
Node current = start;
// Skip nodes until you reach the position
for (int i = 0; i < index; i++)
{
current = current.Next;
}
// Save next node
Node next = current.Next;
// Link a new Node which next Node is the one you just saved
current.Next = new Node () { Name = name, Next = next };
}
}
现在试试自己的删除:)。
于 2012-12-03T16:16:39.067 回答