PETULLA MISHRA
PETULLA MISHRA

Reputation: 13

Adding element in the end of linked list is not throwing output when I am setting head as NULL

Here is my c++ code which inserts an element in the NULL list and then adds an element in the end. But I am unable to find what went wrong with my code. Function insert works fine but when function end is called it returns an empty linked list.

#include <bits/stdc++.h>
using namespace std;


class Node
  {
       public :
       int data;
       Node* next;
  };
  Node * insert(Node* head, int data)
  {
     Node* new_node= new Node();
     new_node->data = data;
     new_node->next = head;
     return new_node;
  }
  Node * end(Node *head, int data)
 {
    Node* ptr = head;
    Node* temp = new Node();
    temp->data=data;
    temp->next=NULL;
    while(ptr!=NULL){
         ptr = ptr->next;
    }
     ptr->next = temp;

    }
    void display(Node * head)
  {
    Node * temp = head;
    while(temp != NULL)
  {
    cout<<temp->data<<" ";
    temp = temp->next;
  }
  }
   int main()
  {
   Node * head = NULL;

   head = insert(head, 1);
   head = end(head, 8);
   display(head);

   return 0;
  }

Upvotes: 1

Views: 53

Answers (1)

kadina
kadina

Reputation: 5372

There is a small issue in your code as below in while loop.

while(ptr!=NULL){
         ptr = ptr->next;
}
ptr->next = temp;

You are checking ptr!= NULL. That means while loop will exit when ptr is NULL and you are doing NULL->next = temp; which is wrong.

And one more issue.

You declared end function will return Node * but you are not returning any thing.

Modified code as below.

#include <bits/stdc++.h>
using namespace std;


class Node
{
    public :
        int data;
        Node* next;
};

Node * insert(Node* head, int data) {
    Node* new_node= new Node();
    new_node->data = data;
    new_node->next = head;
    return new_node;
}

Node * end(Node *head, int data) {
    Node* ptr = head;
    Node* temp = new Node();
    temp->data=data;
    temp->next=NULL;
    
    if(ptr == NULL) {
        return temp;
    }
    
    while(ptr->next!=NULL){
        ptr = ptr->next;
    }

    ptr->next = temp;
    return head;
}

void display(Node * head) {
    Node * temp = head;
    while(temp != NULL)
    {
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}

int main() {
    Node * head = NULL;

    head = insert(head, 1);
    head = end(head, 8);
    display(head);

    return 0;
}

Upvotes: 2

Related Questions