Search code examples
c#doubly-linked-list

How can I remove the first and last Node from doubly linked list?


I have a homework to write a method that will remove the FIRST Node and return its value in a doubly linked list in O(1), and one more method to remove the LAST Node in doubly linked list and return its value in O(1). This is what I did so far.

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;
    }
}

Solution

  • Here's a quick solution I came out with, trying to use your syntax:

    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;
    }