By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,227 Members | 1,290 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,227 IT Pros & Developers. It's quick & easy.

doubly link list in c++

P: 1
Hi..Im writting a doubly link list in c++,compiled with Turbo c++, but my Add_at_first method seems not working,i couldnt find any problem in the code...
here is the code :
Expand|Select|Wrap|Line Numbers
  1. #include <iostream.h>
  2. class node
  3. {  friend class linklist;
  4.   public :    int num;
  5.     node *next;
  6.     node *prev;
  7. };
  8. class linklist{
  9.     public :
  10.     void add_at_first();
  11.  
  12.     private :
  13.     node *first;
  14.     node *last;
  15. };
  16. //*******Add At First**
  17. void linklist :: add_at_first()
  18. {  
  19.    node *temp;
  20.    temp = new node();
  21.    temp ->prev=temp ->next=NULL;
  22.    cout <<"Please Enter A Number :"<< endl;
  23.    cin >> temp -> num;
  24.  
  25.    if(first ==last==NULL)// if the list is empty
  26.    {
  27.       first = last=temp;
  28.    }
  29.    else
  30.    {  
  31.       first -> prev =temp;
  32.       temp -> next = first;
  33.       first = temp;
  34.    }
  35. }
waitting for ur guidance, Thanksss..
Feb 22 '07 #1
Share this Question
Share on Google+
4 Replies


Ganon11
Expert 2.5K+
P: 3,652
Well, in a doubly-linked list, you probably shouldn't need last - to find the last node, you code just use first->prev.

Next, if the list is not empty, you are adjusting first and temp - but you will need to change last (or, if you follow the first example, first->prev) to point forward to temp.
Feb 22 '07 #2

Banfa
Expert Mod 5K+
P: 8,916
Well, in a doubly-linked list, you probably shouldn't need last - to find the last node, you code just use first->prev.
Only true if your list is circular as well as doubly linked.
Feb 27 '07 #3

Ganon11
Expert 2.5K+
P: 3,652
Only true if your list is circular as well as doubly linked.
...right. I keep forgetting to distinguish the two.
Feb 27 '07 #4

Banfa
Expert Mod 5K+
P: 8,916
...right. I keep forgetting to distinguish the two.
Ah, not all four legged animals are cows :D
Feb 27 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.