dman773
dman773

Reputation: 1

Cannot Insert Item into Linked List

void LinkedList::insert(int num, int pos) {
  Node *newNode = new Node;
  newNode->data = num;
  newNode->next = NULL;
  if(pos == 0) {
    newNode->next = head;
    head = newNode;
  }
  else {
    Node *temp = head;
    for (int i = 1; i < pos-1; ++i) {
      if (temp != NULL) {
        temp = temp->next;
      }
    }
    if (temp != NULL) {
      newNode->next = temp->next;
      temp->next = newNode;
    }
    else {
      cout << " The previous node is full.";
    }
  }
}

This is my insert function. The code that runs in main.cpp is:

// adding through insert
    nums.insert(1, 0);
    nums.insert(5, 4);
    nums.insert(3, 7);

And the output is:

List after append: 
8   6   7   8   0   9

List after inserting: 
1   8   6   5   7   8

As you can see, something is getting overwritten, or the end of the list just gets cut off. I have searched the internet for hours to no avail. The output needs to increase the length of the list and not overwrite anything. Any help would be appreciated.

Upvotes: 0

Views: 60

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

The problem is this for loop

for (int i = 1; i < pos-1; ++i) {
  if (temp != NULL) {
    temp = temp->next;
  }
}

Let's assume that pos is equal to 2. In this case the loop will not iterate and temp will be equal to head. So the new node will be inserted before the second mode instead to be inserted before the third node.

You need to write

for (int i = 1; temp != nullptr && i < pos; ++i) {
    temp = temp->next;
}

Also instead of writing this message

 cout << " The previous node is full.";

(it is the caller of the function should decide whether to output a message) I would declare the function like

bool LinkedList::insert(int num, int pos) {

and return either true or false dependent on whether a node was inserted.

Upvotes: 1

Related Questions