[c++] Insert node at a certain position in a linked list C++

I'm trying to insert a node at a certain position. In my code, the numbers with position 1 is only being inserted (basically at the beginning of the linked list) and it is not inserting any data with position 2. Is there something wrong with temp2? When I ran the program it is not pointing to anything I think.

I know how much you guys hate homework problems being asked here but I just don't know what is wrong with my program. I'm just a beginner at this and my teacher didn't explain linked list well.

The code is below.

-The output that I'm getting is 8 7

-I would want it to read 8 6 7 5 where 6 and 5 are inserted at position 2

/*
Insert node at a given positon in a linked list.
First element in the linked list is at position 0
*/

#include<stdlib.h>
#include<stdio.h>

struct Node
{
   int data;
   struct Node* next;
};

struct Node *head;

void Insert(int data, int n)
{
   Node* temp1 = new Node();
   temp1->data = data;
   temp1->next = NULL;
   if (n == 1){
    temp1->next = head;
    head = temp1;
    return;
   }
   Node* temp2 = new Node();
   for (int i = 0; i < n-2; i++){// i feel like it doesn't even go through this loop
    temp2 = temp2->next;
   }
   temp1->next = temp2->next;
   temp2->next = temp2;
}
void print()
{
    Node* temp = head;
    while(temp != NULL){
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}
int main()
{
    head = NULL; //empty linked list
    Insert(7,1); //List: 7     
    Insert(5,2); //List: 7,5   
    Insert(8,1); //List: 8,7,5 
    Insert(6,2); //List: 8,6,7,5      
    print();
system("pause");
} 

This question is related to c++ insert linked-list position nodes

The answer is


 void addToSpecific()
 {
 int n;   
 int f=0;   //flag
 Node *temp=H;    //H-Head, T-Tail
 if(NULL!=H)  
 {
    cout<<"Enter the Number"<<endl;
    cin>>n;
    while(NULL!=(temp->getNext()))
    {
       if(n==(temp->getInfo()))
       {
      f=1;
      break;
       }
       temp=temp->getNext();
    }
 }
 if(NULL==H)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    T=H=nn;
 }
 else if(0==f)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    T->setNext(nn);
    T=nn;
 }
 else if(1==f)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    nn->setNext((temp->getNext()));
    temp->setNext(nn);
 }
 }

Node* InsertNth(int data, int position)
{
  struct Node *n=new struct Node;
  n->data=data;  
  if(position==0)
  {// this will also cover insertion at head (if there is no problem with the input)

      n->next=head;
      head=n;
  }

  else
  {
      struct Node *c=new struct Node;
      int count=1;
      c=head;
      while(count!=position)
      {
          c=c->next;
          count++;
      }
      n->next=c->next;
      c->next=n;

  }
    return ;
}

Insert an element at very beginning position. case-1 when the list is empty. case-2 When the list is not empty.

    #include<iostream>

using namespace std;

struct Node{
int data;
Node* next; //link == head =stored the address of the next node
};

Node* head;  //pointer to Head node with empty list

void Insert(int y);
void print();

int main(){
    head = nullptr; //empty list
    int n,y;
    cout<<"how many number do you want to enter?"<<endl;
    cin>>n;
    for (int i=0;i<n;i++){
        cout<<"Enter the number "<<i+1<<endl;
        cin>>y;
        Insert(y);
        print();
    }
}

void Insert(int y){
    Node* temp = new Node(); //create dynamic memory allocation
    temp->data = y;
    temp->next = head; // temp->next = null; when list is empty
    head = temp;
}

void print(){
    Node* temp = head;
    cout<<"List is: "<<endl;
    while(temp!= nullptr){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
    cout<<endl;
}

Try this function.

structure of node object:

class Node
{
private:
    int data;
    Node *next;

public:
    Node(int);
    ~Node();
    void setData(int);
    int getData();
    void setNext(Node*);
    Node* getNext();
};

Implementation of the function:

Returning a status value is always a god practice, constants defined here are meant for debugging/logging the application usage.

//constants
static int const SUCCESS = 0;
static int const FAILURE = 1;
static int const NULL_OBJ = 2;
static int const POS_EXCEED = 3;

int addAt(int data, int pos){
    Node *tmp = new Node(data);
    if (tmp == NULL){
        //print for debugging only.
        cout << "Object not created. Out of memory maybe" << endl;
        return NULL_OBJ;
    }
    if (pos == 0){
        // add at beginning
        tmp->setNext(this->head);
        this->head = tmp;
        return SUCCESS;
    }else{
        // add element in between or at end
        int counter = 1;
        Node* currentNode = this->head;
        while (counter < pos && currentNode->getNext() != NULL){
            currentNode= currentNode->getNext();
            counter++;
       }
       tmp->setNext(currentNode->getNext());
       currentNode->setNext(tmp);
       return SUCCESS;
   }
   cout << "Failed due to unknown reason.";
   return FAILURE;
}

Assumption here is that, you will call the function after validating the inputs (data and position). Though we can validate the parameters inside the function, it is not a good practice.

Hope this helps.


For inserting at a particular position k, you need to traverse the list till the position k-1 and then do the insert.

[You need not create a new node to traverse to that position as you did in your code] You should traverse from the head node.


Node* insert_node_at_nth_pos(Node *head, int data, int position)
{   
    /* current node */
    Node* cur = head;

    /* initialize new node to be inserted at given position */
    Node* nth = new Node;
    nth->data = data;
    nth->next = NULL;

    if(position == 0){
        /* insert new node at head */
        head = nth;
        head->next = cur;
        return head;
    }else{
        /* traverse list */
        int count = 0;            
        Node* pre = new Node;

        while(count != position){
            if(count == (position - 1)){
                pre = cur;
            }
            cur = cur->next;            
            count++;
        }

        /* insert new node here */
        pre->next = nth;
        nth->next = cur;

        return head;
    }    
}

I had some problems with the insertion process just like you, so here is the code how I have solved the problem:

void add_by_position(int data, int pos)
  {
        link *node = new link;
        link *linker = head;

        node->data = data;
        for (int i = 0; i < pos; i++){
            linker = linker->next;
        }
        node->next = linker;
        linker = head;
        for (int i = 0; i < pos - 1; i++){
            linker = linker->next;
        }
        linker->next = node;
        boundaries++;
    }

Just have something like this where you traverse till the given position and then insert:

void addNodeAtPos(int data, int pos)
{
  Node* prev = new Node();
  Node* curr = new Node();
  Node* newNode = new Node();
  newNode->data = data;

  int tempPos = 0;   // Traverses through the list

  curr = head;      // Initialize current to head;
  if(head != NULL)
  {
    while(curr->next != NULL && tempPos != pos)
    {
        prev = curr;
        curr = curr->next;
        tempPos++;
    }
    if(pos==0)
    {
       cout << "Adding at Head! " << endl;
       // Call function to addNode from head;
    }
    else if(curr->next == NULL && pos == tempPos+1)
    {
      cout << "Adding at Tail! " << endl;
      // Call function to addNode at tail;
    }
    else if(pos > tempPos+1)
      cout << " Position is out of bounds " << endl;
     //Position not valid

    else
    {
        prev->next = newNode;
        newNode->next = curr;
        cout << "Node added at position: " << pos << endl;
    }
 }
 else
 {
    head = newNode;
    newNode->next=NULL;
    cout << "Added at head as list is empty! " << endl;
 }
}

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to insert

How to insert current datetime in postgresql insert query How to add element in Python to the end of list using list.insert? Python pandas insert list into a cell Field 'id' doesn't have a default value? Insert a row to pandas dataframe Insert at first position of a list in Python How can INSERT INTO a table 300 times within a loop in SQL? How to refresh or show immediately in datagridview after inserting? Insert node at a certain position in a linked list C++ select from one table, insert into another table oracle sql query

Examples related to linked-list

Creating a node class in Java Simple linked list in C++ Insert node at a certain position in a linked list C++ Printing out a linked list using toString How to work with string fields in a C struct? JTable - Selected Row click event When to use HashMap over LinkedList or ArrayList and vice-versa C: How to free nodes in the linked list? Java how to sort a Linked List? C linked list inserting node at the end

Examples related to position

How does the "position: sticky;" property work? React Native absolute positioning horizontal centre RecyclerView - Get view at particular position RecyclerView - How to smooth scroll to top of item on a certain position? How to find index of STRING array in Java from a given value? Insert node at a certain position in a linked list C++ How to position the Button exactly in CSS Float a DIV on top of another DIV Iframe positioning css - position div to bottom of containing div

Examples related to nodes

How to restart kubernetes nodes? Creating a node class in Java Insert node at a certain position in a linked list C++ Node.js server that accepts POST requests What is the difference between tree depth and height? Why is NULL undeclared?