我正在尝试通过它的值从LinkedList中删除一个节点,但它似乎不起作用。 LinkedList类(带节点):
public class Node<T>
{
private T info;
private Node<T> next;
public Node(T x, Node<T> next)
{
this.info = x;
this.next = next;
}
public Node<T> GetNext()
{
return this.next;
}
public void SetNext(Node<T> next)
{
this.next = next;
}
public T GetInfo()
{
return this.info;
}
public void SetInfo(T x)
{
this.info = x;
}
public override string ToString()
{
return this.info.ToString();
}
}
public class List<T>
{
private Node<T> first;
public List()
{
this.first = null;
}
public Node<T> GetFirst()
{
return this.first;
}
public Node<T> Add(Node<T> pos, T x)
{
Node<T> temp = new Node<T>(x, null);
if (pos == null)
{
temp.SetNext(this.first);
this.first = temp;
}
else
{
temp.SetNext(pos.GetNext());
pos.SetNext(temp);
}
return temp;
}
public Node<T> Remove(Node<T> pos)
{
if (this.first == pos)
this.first = pos.GetNext();
else
{
Node<T> prevPos = this.GetFirst();
while (prevPos.GetNext() != pos)
prevPos = prevPos.GetNext();
prevPos.SetNext(pos.GetNext());
}
Node<T> nextPos = pos.GetNext();
pos.SetNext(null);
return nextPos;
}
public override string ToString()
{
string str = "[";
Node<T> pos = this.first;
while (pos != null)
{
str += pos.GetInfo().ToString();
if (pos.GetNext() != null)
str += ", ";
pos = pos.GetNext();
}
str += "]";
return str;
}
}
这就是功能:
public void Del(string info)
{
Node<T> previousNode = null, obsoleteNode = null, nextNode = null;
Node<T> pos = this.first;
while (pos != null)
{
if (pos == this.first && this.first.GetInfo().ToString() == info)
{
Node<T> temp = pos;
this.first = this.first.GetNext();
temp = null;
}
else
{
previousNode = pos;
if (previousNode != null)
obsoleteNode = previousNode.GetNext();
if (nextNode == null)
nextNode = pos.GetNext().GetNext();
if (obsoleteNode != null)
{
if (obsoleteNode.GetInfo().ToString() == info)
previousNode.SetNext(nextNode);
}
}
pos = pos.GetNext();
}
}
在VS autos中,它显示obsoleteNode实际上是null但我无法理解为什么。 所有其他值都没关系,除了pos之外,它会以某种方式获取列表中的最后一个节点而不是第一个节点,但是this.first本身是可以的。 可能是什么问题?