如何删除第一个IntNode
本文关键字:第一个 IntNode 删除 何删除 | 更新日期: 2023-09-27 18:13:51
class IntNode
{
public int value { get; set; }
public IntNode next { get; set; }
public IntNode(int value)
{
this.value = value;
this.next = null;
}
public IntNode(int value, IntNode next)
{
this.value = value;
this.next = next;
}
public bool HasNext()
{
return (next != null);
}
public override string ToString()
{
if (this.HasNext())
return value + "-->" + next;
else
return value + "";
}
}
所以如果我想删除给定列表开头的第4个节点:
IntNode pos = head.next;
IntNode prev = head;
int counter = 0;
while (pos != null)
{
if (counter == 4) prev.next = pos.next;
prev = pos;
pos = pos.next;
}
但是我想删除第一个节点(当counter为0时),我该怎么做?谢谢。
像这样的东西应该为您做:
while (pos != null)
{
if ( counter == 0 )
{
head = head.next;
prev = head;
}
else
{
prev.next = pos.next;
}
}
public void Remove(int index) {
if(head != null)
{
if(index == 0)
{
head = head.next;
}
else
{
IntNode pos = head.next;
IntNode prev = head;
while (pos != null)
{
--index;
if (index == 0)
{
prev.next = pos.next;
break;
}
prev = pos;
pos = pos.next;
}
}
}
}