add to doubly linked list

how can i add to doubly linked list

Page 1 of 1

1 Replies - 4136 Views - Last Post: 30 September 2009 - 02:22 PM Rate Topic: -----

#1 hedaya  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 30-September 09

add to doubly linked list

Posted 30 September 2009 - 01:14 PM

is this code right or not
/////////add node//////////
node *add_node(node *head,node *n)
{

//check for empty list //
if(head==NULL)
{
head=n;
return head;


}
//check for first node ////
if(strcmp(n->NAME,head->NAME)<0)
{
head->back=n;
n->forward=head;
n->back=NULL;
head=n;
return head;
}

//general case//
node *p;
p=head;
while (p!=NULL)
{
if(strcmp(n->NAME,p->NAME)<0)
{
	n->forward=p;
n->back=p->back;
p->back=n;
n->back->forward=n;
}
else

p=p->forward;
}

//last case
n->forward=p;
n->back=p->back;
p->back->forward=n;

return head;
}


*** MOD EDIT: Added code tags. Please :code: ***

This post has been edited by JackOfAllTrades: 30 September 2009 - 02:18 PM


Is This A Good Question/Topic? 0
  • +

Replies To: add to doubly linked list

#2 wildgoose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 67
  • View blog
  • Posts: 468
  • Joined: 29-June 09

Re: add to doubly linked list

Posted 30 September 2009 - 02:22 PM

First of all. One of the reasons to have a double linked list is so you can search from the beginning, AND the end.
Where's the tail pointer?

You insert into the middle, and keep searching? EXIT!


Last p is NULL, so why are you using it?
For last, you either use taill, or always remember the one just before the current one!

As a rule, I tend to do the links on the new node first, then splice it in.
Also to keep my insertion/removal code simple I like to place a node header flat in the parent, and it will then look like just another node. Thus the insertion removal logic is combined, and not three separate cases!

This post has been edited by wildgoose: 30 September 2009 - 02:27 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1