Pieter Berkel
Pieter Berkel

Reputation: 59

how do I add a node before the tail in doubly linked list?

Example: I got these nodes: 1, 2, 3, 3
Now I want to add another node: 3.
What happens now is: 1, 2, 3, 3, 3(new one).
But what I want is: 1, 2, 3(new one), 3, 3

What to do?

    if (H == null)
        {
            H = N;
            T = N;
        }
        else if (H.freq >= freq) //add before the header
        {
            N.next = H;
            H.prev = N;
            H = N;
        }
        else if (T.freq < freq) // add after the tail
        {
            N.prev = T;
            T.next = N;
            T = N;
        }
        else //merge between head and tail
        {
            W = H;
            while (freq > W.freq)
            {
                W = W.next;
            }
            N.next = W;
            N.prev = W.prev;
            W.prev.next = N;
            W.prev = N;
        }

Upvotes: 1

Views: 309

Answers (1)

Azad Cebiyev
Azad Cebiyev

Reputation: 71

You can use Find and AddAfter methods:

LinkedListNode<int> node = linked.Find(2);
linked.AddBefore(node, 3);

The main point is to use AddAfter method.

Upvotes: 1

Related Questions