Store/Print Linked list
Nov 22, 2015 at 10:51pm UTC
Am I not storing my linked list correctly? Or am I just not printing correctly? Can any direct me to what I am doing incorrectly? The only value that I get printed out is the 12. Thank you for any help/advice.
list.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#ifndef LIST_H
#define LIST_H
#include <iostream>
using namespace std;
class LinkedList
{
private :
struct Node
{
int data;
Node * next;
Node * prev;
};
Node * head, * tail;
public :
LinkedList();
bool add(int val);
void print() const ;
};
#endif
list.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include "list.h"
LinkedList::LinkedList()
{
}
bool LinkedList::add(int val)
{
Node * newNode;
newNode = new Node; //Creates new node
newNode->data = val; //Stores val
newNode->next = nullptr ;
head = nullptr ;
if (head == nullptr )
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode; //Insert new node at the end of the list
tail = newNode;
}
return head;
}
void LinkedList::print() const
{
Node * current;
current = head;
while (current != nullptr )
{
cout << current->data << endl;
current = current->next;
}
}
app.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include "list.h"
int main()
{
LinkedList aList;
aList.add(3);
aList.add(10);
aList.add(1);
aList.add(7);
aList.add(9);
aList.add(12);
aList.print();
system("pause" );
return 0;
}
Nov 23, 2015 at 4:30am UTC
Looks like I got it figured out. For some reason I had head = nullptr
which was always making head == nullptr
always true..
Topic archived. No new replies allowed.