我有一个家庭作业,编写了一种方法,该方法将删除FIRST节点并在O(1)的双向链表中返回其值,还有另一种方法在双向链表中删除LAST Node并在O(1)中返回其值O(1)。这是我到目前为止所做的。
class DoubleList<T>
{
DNode _start;
DNode _end;
public void AddFirst(T value)
{
DNode tmp = new DNode(value);
tmp._next = _start;
tmp._prev = null;
if (_start != null)
{
_start._prev = tmp;
}
_start = tmp;
if (_start._next == null)
_end = tmp;
}
public void AddLast(DoubleList<T> doubleyList, T value)
{
DNode tmp = new DNode(value);
if (_start == null)
{
AddFirst(value);
return;
}
DNode lastNode = GetLastNode(doubleyList);
lastNode._next = tmp;
tmp._prev = lastNode;
_end._next = tmp;
_end = tmp;
}
}
答案 0 :(得分:2)
C#中已经有一个具有这些方法的类doubleList。
答案 1 :(得分:0)
这是我想出的一种快速解决方案,尝试使用您的语法:
public DNode RemoveHead()
{
// "Save" the current head to return it at the end
DNode head = _start;
if (_start != null)
{
// The start becomes the element next to the current one
_start = _start._next;
// The first node has to have no "previous" one
if (_start != null) _start._prev = null;
}
return head;
}
public DNode RemoveTail()
{
// "Save" the current tail to return it at the end
DNode tail = _end;
if (_end != null)
{
// The end becomes the element previous to the current one
_end = _end._prev;
// The last node has to have no "next" one
if (_end != null) _end._next = null;
}
return tail;
}
答案 2 :(得分:0)
从上面提供的解决方案中进一步了解,我建议您也改变双向链表的大小,以便您更加关注空间复杂度和时间复杂度。您可以在下面找到我的解决方案,删除列表中的第一个或最后一个节点以及调整计数。
public void RemoveFirst()
{
if (Head == null && Tail == null) throw new InvalidOperationException();
Head = Head.Next;
Head.Previous = null;
Count--;
}
public void RemoveLast()
{
if (Head == null && Tail == null) throw new InvalidOperationException();
Tail = Tail.Previous;
Tail.Next = null;
Count--;
}