我编写了一个C#代码,用于将数据插入双向链表并删除节点。它正在工作,我可以从最后一个节点到第一个节点遍历列表。但我不能遍历从第一个节点到最后一个节点的列表。我找不到我犯的错误。以下是我的代码。
class Node
{
public string data { get; set; }
public Node next { get; set; }
public Node previous { get; set; }
public Node(string data)//first node)
{
this.data = data;
this.next = null;
this.previous = null;
}
public Node(string data, Node next,Node previous)
{
this.data = data;
this.next = next;
this.previous = previous;
}
}
class doublyLinkedList
{
private Node first;
private Node last;
private int size;
public doublyLinkedList()
{
this.first = null;
this.last = null;
this.size = 0;
}
public bool isEmpty
{
get { return this.size == 0; }
}
public int count
{
get { return this.size; }
}
public void Add(string o)
{
Node current = this.last;
if (this.isEmpty)
{
this.first = new Node(o);
this.last = new Node(o);
}
else
{
current.next = new Node(o, current.next,current);
last = current.next;
Console.WriteLine("first " + first.data + "last " + last.data + "previous " + last.previous.data);
}size++;
}
public object getFirst()
{
return first.data;
}
public string remove()
{
Node current = this.last;
current.previous.next = null;
object removedElement = current.data;
string reEle = ((String)(removedElement).ToString());
current = current.previous;
size--;
return reEle;
}
public void TraverseFront()
{
Node current = this.first;
string str = current.data;
Console.WriteLine("first " + str);
Node current1 = first.next;
string str1 = first.next.data;
string question = str + str1;
Console.WriteLine(question)
}
}
答案 0 :(得分:1)
您插入第一个对象时出现问题。您需要将最后一个设置为与第一个相同的实例,因为当您断开第一个对象时(this.first.next始终为null),请将其更改为:
this.last = new Node(o);
为:
this.last = this.first;