user12810172
user12810172

Reputation:

C++: How to insert node at a certain position in a linked list?

Need to insert a new node that contains the given data value, such that the new node occupies the offset indicated. Any nodes that were already in the list at that offset and beyond are shifted down by one.It should have the same effect as appending and no effect if it is beyond the end of the list.

void LinkedList::InsertData(int offset, int data){
  shared_ptr<node> curr(top_ptr_);
  shared_ptr<node> temp(new node);
  temp->data = data;
  temp->next = shared_ptr<node>(NULL);

  if(offset == 0) {
    temp->next = top_ptr_;
    top_ptr_ = temp;
  }
  offset--;
  while(offset-- && curr->next!=NULL)  {
    curr = curr->next;
  }
  temp->next = curr->next;
  curr->next = temp;
}

Upvotes: 0

Views: 366

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596387

You are close. Since you are handling offset==0 specially, you need to move your while loop inside of an else block, eg:

void LinkedList::InsertData(int offset, int data) {
  if (offset < 0)
    return; // or throw...

  shared_ptr<node> temp(new node);
  temp->data = data;

  if (offset == 0) {
    temp->next = top_ptr_;
    top_ptr_ = temp;
  }
  else {
    shared_ptr<node> curr = top_ptr_;
    while ((--offset > 0) && curr->next) {
      curr = curr->next;
    }
    temp->next = curr->next;
    curr->next = temp;
  }
}

Live Demo

However, InsertData() can be simplified by eliminating the if (offset == 0) block altogether, eg:

void LinkedList::InsertData(int offset, int data) {
  if (offset < 0)
    return; // or throw...

  shared_ptr<node> temp(new node);
  temp->data = data;

  shared_ptr<node> *curr = &top_ptr_;

  while ((offset-- > 0) && *curr)
    curr = &((*curr)->next);

  temp->next = *curr;
  *curr = temp;
}

Live Demo

Upvotes: 1

Related Questions