Search code examples
c++linked-listtraversal

can not traverse a linked list


I am new at linked list. Recently I have created a linked list and tried to do some operations on it like insertion , deletion e.tc . But I failed to traverse the linked list. I guess the head pointer is changing during the insertion .I have faced this type of problem several time. Help me to figure out.

#include<bits/stdc++.h>
using namespace std ;
struct node
{
    int data ;
    struct node* next ;
};

void insertion_end( node* head , int n)
{
    node* temp = new node() ;
    temp->data = n ;
    temp->next = nullptr ;
    node* last = head ;
    if(head == nullptr)
    {
        head =temp ;
    }
    else
    {
        while ( last != nullptr)
        {
            last = last->next ;
        }
        last = temp ;
    }
}

void insertion_front (node* head , int n)
{
    node* temp = new node();
    temp->data = n ;
    temp->next = head ;
    head = temp ;
}

void deletion (node* head , int n)
{
    node* temp ;
    node* temp2 ;
    while(temp->data != n)
    {
        temp = temp->next ;
    }
    if(temp->data != n)
    {
        cout<< "Not found!" <<"\n" ;
    }
    temp2 = temp ;
    temp = temp->next ;
    free(temp2) ;
}

void traverse(node* head)
{
    node* temp = head ;
    while ( temp->next != nullptr)
    {
        cout<< " "<< temp->data << "\n" ;
        temp =temp->next ;
    }
}

int main()
{
cin.tie(NULL);
cout.tie(NULL);

node* head = new node();
head->next = nullptr ;

insertion_end(head , 10);
insertion_end(head , 5463);
insertion_end(head , 474);
insertion_end(head , 5475);
insertion_end(head , 457);
insertion_end(head , 3575);
insertion_front(head , 41234);
insertion_front(head , 68976);
insertion_front(head , 23);
insertion_front(head , 57);

deletion(head , 68976);

traverse( head );

return 0 ;

}


Solution

  • Your insert function should be:

    void insertion_front(node** head, int n)
    {
        node* temp = new node();
        temp->data = n;
        temp->next = *head;
        *head = temp;
    }
    

    And when you call the function:

    insertion_front(&head, 41234);