1

So this new node is supposed to be inserted after the last node. I can't figure out why that is not happening. Note: The list has multiple elements before this function is called (approx 5) so as of now it only has to work for that case. The last node should point to the top node and the top->prev pointer should point to the last node. Where have I gone wrong? I'm assuming that its wrong by the way because the last node never prints when the print function is called

void CircularDLL::insertAfterLast (int id, string name, string email, int age)
{
 Node* N=new Node;

 N->stId=id;
 N->stName=name;
 N->stEmail=email;
 N->stAge=age;

 Node* Q=top;

 while(Q->next!=top)//get to the last node
 {
  Q=Q->next;
 }
 cout<<"Q next is top now"<<endl;
 Q->next=N;
 N->prev=Q;
 N->next=top;
 top->prev=N;

}
2
  • 2
    Can you post your print function? Maybe it's what's incorrect. Commented May 6, 2011 at 23:21
  • 5
    If it is circular double-linked list, why not use top->prev to get to the last node? Commented May 6, 2011 at 23:25

1 Answer 1

3

This code has a few issues. First, if you're going to do "insertAfterLast" frequently, you should use "top->prev" to get a pointer to the last element in constant time; otherwise building a list will require quadratic (O(n^2)) time. Second, in any real project implementing a circular linked list from scratch is almost certainly a bad idea - instead you want to stick with a mature STL-compliant container like std::deque or Boost's circular_buffer.

Assuming you really do want to do this, and you're not concerned about empty lists, your function above appears to already be completely correct. Most likely the problem is either that your initial list before you begin is malformed, or more likely, that when you iterate over the list to print it out at the end, you're skipping the last element. The right way to iterate over a circularly linked list is like this (adapted from Wikipedia):

Node* Q = top;
do {
    cout << Q->stId << endl;
    Q = Q->next;
} while (Q != top);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.