I'm trying to remove a Node from LinkedList by it's value however it doesn't seem to work. LinkedList class (with node):
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;
}
}
That's the function:
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();
}
}
In VS autos it shows that obsoleteNode is actually null but i can't understand why. All other values are okay, except pos, it gets somehow the last node in the list instead of first but the this.first himself is okay. What can be the problem?
精彩评论