Gaurav Singh
Gaurav Singh

Reputation: 17

Why is this linked list program not giving any output?

So I made these two simple functions regarding linked lists. One adds a node at the front and the other just displays the linked list in a sequence front to end. I'm wondering why this code wouldn't give me any output.

#include <iostream>
using namespace std;

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

void addFront(Node *head, int item)
{
    Node *temp = new Node();
    temp->data = item;
    temp->next = head;
    head = temp;
}
void traverse(Node *head)
{
    Node *temp = head;
    while(temp!=NULL)
    {
        cout << temp->data << " ";
        temp = temp->next;
    }
}

int main()
{
    addFront(head, 1);
    addFront(head, 2);
    addFront(head, 3);
    traverse(head);
}

Upvotes: 1

Views: 74

Answers (2)

Chetan
Chetan

Reputation: 21

Argument of addFront is input as well as output. (Node *head) It needs to be passed as referenced

Upvotes: 2

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12383

You're operating on a copy of head pointer in addFront(). You have to pass a pointer to pointer:

void addFront(Node **head, int item)

The entire code could look like this:

#include <iostream>
using namespace std;

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

void addFront(Node **head, int item)
{
  Node *temp = new Node();
  temp->data = item;
  temp->next = *head;
  *head = temp;
}

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

int main()
{
  addFront(&head, 1);
  addFront(&head, 2);
  addFront(&head, 3);
  traverse(head);
}

Upvotes: 3

Related Questions