简体   繁体   中英

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM