0

When i try to run my program, it put the item = 4 in the last position instead of the nth position i want. I tried to find all over the internet but I couldn't find one. Please help explain it to me what to do and why since I'm still new to c++ xD

Node* node;
for(int i=1; i <=3 ; i+=2 ){
if (i = 3){
current->next =  new Node(4);
current = current->next;}
else{
current = current->next;}}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Amir
  • 21
  • 3

2 Answers2

1

i = 3 is an assignment. No matter what value i had before, i will be set to 3, and anything non-zero will be interpreted as true, causing the if to always enter its body, and never the else.

Read What is a debugger and how can it help me diagnose problems? to learn how you can easily spot such issues in your code.

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43
0

You need to take a look at the container holding the Node items. For a singly-linked-list there should be a pointer marking the beginning of the list eg: linked_list.BEGIN.

The function in this snippet would insert a node item at a specified index

bool insert(int index, item value)
{
  // invalid index...
  if (index < 0) return false;

  // list is empty and index is 0...
  if ((index == 0) && (linked_list.BEGIN == nullptr))
  {
    linked_list.BEGIN = new Node(value);
    return true;
  }

  Node *current = linked_list.BEGIN, *prev = nullptr;
  int i = 0;

  for (; (current != nullptr); ++i)
  {
    if (i == index) // index is found (index < SIZEOF(linked_list))...
    {
      Node *ptr = new Node(value);
      ptr->next = current;
      if (prev != nullptr) prev->next = ptr;
      else linked_list.BEGIN = ptr;
      break;
    }
    else // index not found yet...
    {
      prev = current;
      current = current->next;
    }
  }

  // index is found (index == SIZEOF(linked_list))
  if ((i == index) && (current == nullptr))
  {
    prev->next = new Node(value);
  }

  return (i == index);
}

Note: This snippet is for illustration and not actual code