Reputation: 527
This is my first time working with linked lists and I was wondering where exactly am I going wrong in my understanding? I put comments before each line to show what I am trying to do based on my current understanding of linked lists. Based on my while loop I feel that I am doing something wrong because I can not get all the values to print out in the list.
#include <iostream>
#include <string>
struct node{
int data;
node* next;
};
int main()
{
//creating a head pointer
node* head = NULL;
//creating new node
node* temp = new node;
//giving new node data(2)
temp->data = 2;
//node does not point to another node
temp->next = NULL;
//pointing head to temp(connecting them)
head = temp;
//creating a new node
node*temp1 = new node;
//giving new node data 3
temp1->data = 3;
//new node is not pointing to anything
temp1->next = NULL;
//connecting temp node to temp1 node
temp = temp1;
//creating a node that will start at head to allow me to print
//all the values in the list by traversing through it
node* trav = new node;
//setting trav equal to head so it starts from the beginning of
//list
trav = head;
while(trav->next != NULL){
trav = trav->next;
std::cout<<trav->data;
}
}
Upvotes: 2
Views: 73
Reputation: 212929
I think your main problem is here:
//connecting temp node to temp1 node
temp = temp1;
You probably meant:
//connecting temp node to temp1 node
temp->next = temp1;
node* trav = new node;
//setting trav equal to head so it starts from the beginning of
//list
trav = head;
This should just be:
//setting trav equal to head so it starts from the beginning of
//list
node* trav = head;
Upvotes: 1