Latest Lists

How would I insert a new node in a double linked list (c++)?

Okay, kind of simple, but I'm at a loss. I am basically making Nodes in a list. I can make the first one fine, using this: if(this->head==NULL) { Node *newNode = new Node; this->head=newNode; this->tail=newNode; newNode->previous=NULL; newNode->next=NULL; newNode->value = item; cout << newNode->value; } Now, in the else statement, I need a way to insert a node at the head of the list. But I don't know how to do this. So basically I want a way have like a list of head <--------------> tail <-42-> <-45-> ... etc ^ (insert a new value there) Can anyone tell me how I would go about this? Thanks yo.

Public Comments

  1. hm. should the head points always to the first node? should the tail points always to the last node? should node's prev points always to prev? and succ/next to next? then (pseudolang) insert_before(list,node, where) is  if where.prev == null then   node.prev = null   node.next = where   list.head = node   where.prev = node  else   node.prev = where.prev   node.next = where   where.prev = node end you can write insert_after easily (i loved double linked lists of the kind i used to use eons ago, where the list is sortof a union between listnode and simply node, and there was a trick with pointers that made them fast and powerful ... )
Powered by Yahoo! Answers