Move a node to the front of a doubly linked list

Oct 10, 2013 at 10:36pm
Hello, everyone. I'm relatively new to doubly linked lists, and I have to write a method that moves a node to the front of one. Here is what I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template<typename T>
void DoublyLinkedList<T>::moveToFront(ListNode<T>* n)
{
  if (head == n) // if n is the head just return
    {
      return;
    }
  else if (tail == n)
    {
      n->prev->next = 0;
      tail = n->prev;
    }
  else // n is in the middle of list
    {
      n->prev->next = n->next;
    }

  // make n the head of the list
  head->prev = n;
  n->next = head;
  n->prev = 0;
  head = n;
}


I've walked through it a few times, and I feel like this correct. However, my program's output is off and I'm guessing this function is the culprit. I think I just need a different pair of eyes to take a look at it. Again, I am pretty new to this, so I haven't gotten linked lists down exactly. Any insight is greatly appreciated.
Oct 11, 2013 at 12:50am
The only thing I see is that you did n->prev->next = n->next but forgot n->next->prev = n->prev.
Oct 11, 2013 at 2:11pm
Thanks for the help!
Topic archived. No new replies allowed.