Not able to output object in linked list - c++

I have created a linked list and in each list consists a node that holds a CarPart object. I believe I have everything working, except outputting the cout. I get the following errors
'CarPart::getPartNumber': non-standard syntax; use '&' to create a pointer to member (carpart.cpp line 34)
'CarPart::getDescription': non-standard syntax; use '&' to create a pointer to member (carpart.cpp line 35)
'CarPart::getPrice': non-standard syntax; use '&' to create a pointer to member (carpart.cpp line 36)
I have tried changing the osstream operator and have not been able to figure out the issue.
Main.cpp
#include "stdafx.h"
#include "List.h"
int main()
{
List partsList;
partsList.push_front(new CarPart("FL2016", "Oil Filter", 18.95));
partsList.push_front(new CarPart("RS12YC", "Spark Plug", 4.15));
partsList.push_front(new CarPart("D5941", "Digital Tire Guage", 12.15));
partsList.push_back(new CarPart("G19216", "Car Wash Solution", 8.15));
partsList.display();
cout << "now we are going to remove the first item in the list" << endl;
system("PAUSE");
partsList.pop_front();
partsList.display();
system("PAUSE");
cout << "now we are going to remove the LAST item from the list" << endl;
partsList.pop_back();
partsList.display();
system("PAUSE");
return 0;
}
List.h
#pragma once
#include "node.h"
class List
{
private:
int listSize;
Node* n;
Node* temp;
Node* head;
Node* tail;
public:
List();
void push_front(CarPart*);
void push_back(CarPart*);
void pop_front();
void pop_back();
void display();
~List();
};
List.cpp
#include "stdafx.h"
#include "List.h"
List::List()
{
}
void List::push_front(CarPart* dat)
{
if (listSize == 0) {
n = new Node;
n->setData(dat);
listSize++;
temp = n;
head = n;
tail = n;
}
else {
n = new Node;
n->setData(dat);
listSize++;
temp = head;
head = n;
n->setNext(temp);
n->setPrevious(nullptr);
temp->setPrevious(n);
temp = n;
}
}
void List::push_back(CarPart* dat)
{
if (listSize == 0) {
n = new Node;
n->setData(dat);
listSize++;
temp = n;
head = n;
tail = n;
}
else {
n = new Node;
n->setData(dat);
listSize++;
temp = tail;
temp->setNext(n);
n->setPrevious(temp);
// SET NEXT TO NULL
temp = n;
tail = temp;
}
}
void List::pop_front()
{
temp = head->getNext();
delete head;
head = temp;
listSize--;
}
void List::pop_back()
{
temp = tail->getPrevious();
delete tail;
tail = temp;
tail->setNext(nullptr);
listSize--;
}
void List::display()
{
Node* test = head;
for (int i = 0; i < listSize; i++) {
cout << test;
}
}
List::~List()
{
}
Node.h
#pragma once
#include "CarPart.h"
class Node
{
private:
CarPart* data;
Node* next;
Node* previous;
public:
Node();
CarPart* getData();
void setData(CarPart*);
void setNext(Node*);
void setPrevious(Node*);
Node* getPrevious();
Node* getNext();
void display();
~Node();
};
Node.cpp
#include "stdafx.h"
#include "Node.h"
Node::Node()
{
}
CarPart* Node::getData()
{
return data;
}
void Node::setData(CarPart* dat)
{
data = dat;
}
void Node::setNext(Node* nextNode)
{
next = nextNode;
}
void Node::setPrevious(Node* prev)
{
previous = prev;
}
Node * Node::getPrevious()
{
return previous;
}
Node * Node::getNext()
{
return next;
}
void Node::display()
{
cout << data;
}
Node::~Node()
{
}
CarPart.h
#pragma once
#include <iostream>
using namespace std;
class CarPart
{
private:
string partNumber;
string description;
double price;
public:
CarPart();
CarPart(string, string, double);
string getPartNumber();
string getDescription();
double getPrice();
~CarPart();
friend ostream& operator<<(ostream& os, CarPart* dt);
};
CarPart.cpp
#include "stdafx.h"
#include "CarPart.h"
CarPart::CarPart()
{
}
CarPart::CarPart(string n, string d, double p)
{
partNumber = n;
description = d;
price = p;
}
string CarPart::getPartNumber()
{
return partNumber;
}
string CarPart::getDescription()
{
return description;
}
double CarPart::getPrice()
{
return price;
}
ostream& operator<<(ostream& os, CarPart* dt)
{
os << dt->getPartNumber;
os << dt->getDescription;
os << dt->getPrice;
return os;
}
CarPart::~CarPart()
{
}
Update
I fixed the error below, but it is not outputting the car parts, the console just shows 00820788008207880082078800820788. I assume it is just the pointer, but not sure what I am doing wrong.

You are calling your get functions incorrectly. You are using dt->getPartNumber; instead of using dt->getPartNumber();

To call a method/function, you always put brackets, even if there is no arguments (dt->getPartNumber()). This line
os << dt->getPartNumber()
means "pass to os the value returned by calling getPartNumber".
Otherwise, it interprets dt->getPartNumber as a pointer to the getPartNumber function, which is a very different beast.
NOTE: For future questions, try to post only the minimum code that causes the error instead of the entire program, and try to mark the line where the error is raised. Google for SSCCE.

Related

double free detected in tcache 2 when initializing a list, crashes upon entry insertion

Reading from a file, each line is stored in a list as an individual row. Each row contains two standard values and a variable amount stored in a list. Therefore each node has two values and a list. Initialization through operator>> works, but as soon as I try to run the loadfile function it crashes with the error: free(): double free detected in tcache 2 Aborted (core dumped)
Here is the code
#include <iostream>
#include "Resource.h"
#include "list.h"
#include "node.h"
using std::cout;
using rows = List<Resource>;
using row = Node<Resource>;
void loadFile(string idata, rows &res)
{
ifstream ifs(idata, ifstream::in);
while (ifs.good())
{
Resource s;
ifs >> s;
row *temp = new Node<Resource>(s);
res.insert(temp);
}
ifs.close();
}
int main()
{
rows resList;
loadFile("data.txt", resList);
cout << resList.getHead()->getValue();
}
this is the source for the class that stores the values, that will be wrapped in a Node template class.
#ifndef RESOURCE_H
#define RESOURCE_H
#include <iostream>
#include <fstream>
#include <string>
#include "list.h"
#include "node.h"
#include <stdio.h>
#include <algorithm>
using std::cout;
using std::istream;
using std::string;
class Resource
{
private:
string Name;
int amt;
List<string> clientList;
public:
Resource(string n, int a) : Name(n), amt(a) {}
Resource(string n) : Resource(n, 0) {}
Resource() : Resource("", 0) {}
string getName()
{
return this->Name;
}
int getAmt()
{
return this->amt;
}
void setName(string n)
{
this->Name = n;
}
void setAmt(int a)
{
this->amt = a;
}
friend ostream &operator<<(ostream &out, const Resource &r)
{
out << r.Name << ";" << r.amt;
List<string> temp = r.clientList;
for (Node<string> *app = temp.getHead(); app != NULL; app = app->getNext())
{
out << ';';
out << app->getValue();
}
return out;
}
friend istream &operator>>(istream &in, Resource &r)
{
string Name;
string amt;
string params;
string tempVar;
getline(in, Name, ';');
getline(in, amt, ';');
getline(in, params, '\n');
const int paramsOriginalLength = count(params.begin(), params.end(), ';');
for (int i = 0; i < paramsOriginalLength; i++)
{
r.clientList.insert(params.substr(0, params.find(';')));
params.erase(0, params.find(';') + 1);
}
r.setName(Name);
r.setAmt(stoi(amt));
return in;
}
};
#endif
EDIT: Since the problem might be caused by the data structure's defintion I will include the source of list.h and node.h
List:
#ifndef LIST_H
#define LIST_H
// Standard Template Linked List - List - by Eduardo Meli - 2020
#include "node.h"
#include <iostream>
using namespace std;
template <class T>
class List
{
private:
int length;
Node<T> *head;
public:
List(int length, Node<T> *head) : length(length), head(head) {}
List() : List(0, NULL) {}
Node<T> *getHead()
{
return this->head;
}
int getLength()
{
return this->length;
}
void insert(T value)
{
Node<T> *app = new Node<T>(value);
this->insert(app);
}
void insert(Node<T> *n)
{
if (head == NULL)
{
head = n;
length++;
return;
}
Node<T> *curr = head;
while (curr->getNext() != NULL)
{
curr = curr->getNext();
}
curr->setNext(n);
length++;
}
void deleteNode(Node<T> *n)
{
if (n == this->getHead())
{
this->head = head->getNext();
this->length = length - 1;
delete n;
return;
}
Node<T> *prev = head;
Node<T> *curr = head->getNext();
while (curr != NULL)
{
if (curr == n)
{
prev->setNext(curr->getNext());
length--;
return;
}
prev = curr;
curr = curr->getNext();
}
}
Node<T> *deleteNode(T value)
{
if (this->seekNode(value))
{
if (head->getValue() == value)
{
Node<T> *temp = head;
head = head->getNext();
length--;
return temp;
}
Node<T> *prev = head;
Node<T> *curr = head->getNext();
while (curr != NULL)
{
if (curr->getValue() == value)
{
prev->setNext(curr->getNext());
length--;
return curr;
}
prev = curr;
curr = curr->getNext();
}
}
return NULL;
}
void print()
{
Node<T> *nk = this->getHead();
while (nk != NULL)
{
cout << nk->getValue() << endl;
nk = nk->getNext();
}
}
~List()
{
Node<T> *ptr;
for (ptr = head; head; ptr = head)
{
head = head->getNext();
delete ptr;
}
}
};
#endif
And node:
#ifndef NODE_H
#define NODE_H
// Standard Template Linked List - Node - by Eduardo Meli - 2020
#include <fstream>
#include <iostream>
using namespace std;
template <class T>
class Node
{
private:
T value;
Node<T> *next;
public:
Node(T value, Node<T> *next) : value(value), next(next) {}
Node(T value) : Node(value, NULL) {}
Node() : Node(0, NULL) {}
T getValue()
{
return this->value;
}
Node<T> *getNext()
{
return this->next;
}
void setValue(T val)
{
this->value = val;
}
void setNext(Node<T> *n)
{
this->next = n;
}
friend ostream &operator<<(ostream &out, const Node &n)
{
out << n.value;
return out;
}
};
#endif

c++ generic singly linked list string print fails

I am implementing a generic singly linked list. It works with char and int, but not for string. What mistake have I made? I get an error:
C2679 binary '<<': no operator found which takes a right-hand operand of type 'T' (or there is no acceptable conversion)
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
template <typename T>
struct Node
{
T data;
Node*next;
//friend class List<T>;
};
template<typename T>
class List
{
public:
List() :headNode{ nullptr } {} // empty list constructor
~List() // destructor
{
Node<T>*current = headNode;
while (current)
{
Node<T>*temp = current;
current = current->next;
delete temp; cout << "\nDeleting Nodes!!!";
}
}
bool empty() const // is list empty?
{
return headNode == nullptr;
}
const T& front() const // get front element
{
return headNode->data;
}
void addFront(const T& e) // add to front of list
{
Node<T>* tempNode= new Node<T>;
tempNode->data = e;
tempNode->next = headNode;
headNode = tempNode;
}
void removeFront()
{
if (empty()) cout << "List is empty" << endl;
else
{
Node<T> *tempNode = headNode;
headNode = tempNode->next;
delete tempNode; cout << "\nDeleting Node!!!";
}
}
void printList()const
{
Node<T>*current = headNode;
while (current)
{
cout << current->data<<" |-> ";
current = current->next;
}
}
private:
Node<T> *headNode;
};
int main()
{
srand(time(NULL));
List<int> mylist;
for (int i = 0; i < 15; ++i)
{
mylist.addFront(rand()%200 + 20);
}
mylist.printList();
mylist.removeFront(); cout << endl;
mylist.printList();
List<string>family;
family.addFront("aaa");
family.addFront("bbb");
family.addFront("ccc");
family.addFront("ddd");
family.printList();
List<char> charlist;
charlist.addFront('a');
charlist.addFront('b');
charlist.addFront('c');
charlist.addFront('d');
charlist.printList();
return 0;
}
You need to include the header <string>.
#include <string>
where the operator << for streams and the class std::string is declared.

C++ adding one line of code after while loop causes an error

I have tried my best to look for an answer that addresses my specific question but unfortunately, I wasn't able to find one that satisfied my needs.
I am writing an assembler in c++ for a language that I made up. Writing the assembler involves two classes that have been causing problems really tough to debug. My debugging techniques have devolved to adding and removing output stream commands like
std::cout << "TEST";
which end up either breaking or fixing the program. The IDE I am using is Xcode.
The two classes that I am working on are a LinkedList class and a SymbolTable class, which I am using as a hash table for symbol resolution.
LinkedList.h
#include <iostream>
using namespace std;
struct Node{
string data;
int address;
Node* next = nullptr;
};
class LinkedList{
private:
Node* main_ptr;
int length;
public:
LinkedList();
void insertNode(string, int);
void deleteNode(string);
void displayList();
bool contains(string, int* = nullptr);
int getLength();
~LinkedList();
};
LinkedList.cpp
#include "LinkedList.h"
LinkedList::LinkedList(){
main_ptr = nullptr;
length = 0;
}
void LinkedList::insertNode(string data, int address){
Node* newNode = new Node;
newNode->data = data;
newNode->address = address;
if (!main_ptr){
main_ptr = newNode;
} else {
newNode->next = main_ptr;
main_ptr = newNode;
}
length++;
}
void LinkedList::deleteNode(string data){
if (main_ptr){
int current_length = length;
if (main_ptr->data == data){
main_ptr = main_ptr->next;
return;
}
Node* q = main_ptr;
Node* p = q;
q = q->next;
while (q){
if (q->data == data){
p->next = q->next;
length--;
return;
}
p = q;
q = q->next;
}
if (current_length == length) cout << "Node was not found" << endl;
} else {
cout << "List is empty, cannot delete node!" << endl;
}
}
void LinkedList::displayList(){
if (!main_ptr){
cout << "List is empty!\n";
} else {
Node* temp = main_ptr;
while (temp){
cout << temp->data;
temp = temp->next;
}
cout << endl;
}
}
bool LinkedList::contains(string data, int* address){
if (main_ptr == nullptr) return false;
else {
Node* temp = main_ptr;
while(temp != nullptr){
if (temp->data == data) {
address = &(temp->address);
return true;
}
temp = temp->next;
}
return false;
}
}
int LinkedList::getLength(){
return length;
}
LinkedList::~LinkedList(){
if (main_ptr){
Node* q = main_ptr;
Node* p = q;
while (q){
q = q->next;
delete p;
p = q;
}
}
}
SymbolTable.h
#include "LinkedList.h"
#include <iostream>
class SymbolTable{
private:
LinkedList table[701];
public:
SymbolTable();
void addEntry(string, int);
void printTable();
bool contains(string, int*);
int convertName(string);
};
SymbolTable.cpp
#include "SymbolTable.h"
SymbolTable::SymbolTable(){
}
void SymbolTable::addEntry(string name, int memory){
int address = convertName(name);
table[address].insertNode(name, memory);
}
void SymbolTable::printTable(){
for (int i = 0; i < 701; i++)
table[i].displayList();
}
bool SymbolTable::contains(string name, int* memory){
return table[convertName(name)].contains(name, memory);
}
int SymbolTable::convertName(string name){
int aggregate = 1;
const char* c_name = name.c_str();
for (int i = 0; i < name.length(); i++){
aggregate *= (int)c_name[i];
}
return aggregate%701;
}
Now comes my actual question. The following is the main function:
#include "Parser.h"
#include "SymbolTable.h"
using namespace std;
int main(int argc, const char * argv[]) {
ifstream inputFile;
ofstream outputFile;
inputFile.open("/Users/Azaldin/Desktop/nand2tetris/projects/06/max/Max.asm");
outputFile.open("/Users/Azaldin/Desktop/nand2tetris/projects/06/max/Max.hack");
Parser a(inputFile);
SymbolTable s;
int commandType = -1;
string command;
int a_position = 16;
int currentLine = 0;
while (a.hasMoreCommands()){
a.advance();
commandType = a.commandType();
command = a.symbol();
if (commandType == 0){
if (!s.contains(command, nullptr)){
s.addEntry(command, a_position);
a_position++;
}
}
if (commandType == 2){
//cout << command << endl;
if (!s.contains(command, nullptr)){
s.addEntry(command, currentLine);
//cout << command << endl;
}
}
currentLine++;
}
string x; //<<<<<<<<<< ADDING THIS LINE BREAKS THE PROGRAM
cout << "Hi";
inputFile.close();
outputFile.close();
return 0;
}
After adding the line pointed to above in the main function, the program breaks.
Upon debugging, the following problem arises from the main thread:
Thread 1:EXC_BAD_ACCESS (code = 1, address=0x25fbfef80)
The chain of commands that leads to this problem:
if (!s.contains(command, nullptr)){ from the main function
return table[convertName(name)].contains(name, memory); from the SymbolTable.cpp "contains" function
if (temp->data == data) { from LinkedList.cpp "contains" function
The rest of the chain command leads to the string class == operator, which then leads to the .size() function on the left-hand side.
Thank You!
The following comment by PaulMcKenzie helped solve the problem:
Also, aggregate *= (int)c_name[i]; -- there is no guarantee that this
will be a positive number, since a character may be signed, thus
giving you values of -1 and below. Thus your return of return
aggregate%701; isn't going to return what you expected (a number >=
0).
It turns out that one of the arguments passed into the convertName function in the SymbolTable class have caused the program to corrupt the memory. I added an if statement to solve the problem.

Linked Lists not properly displaying

I have created a linked list that each node holds a CarPart object. I know that the issue is that I am not properly de-referencing the pointer and it just displays the pointer and not the actual value... problem being is I have not been able to figure out how properly display the car part items to the console.
Per request I have removed any code that does not effect the outcome of what I am trying to do.
Main.cpp
#include "stdafx.h"
#include "List.h"
int main()
{
/*cout << new Node(new CarPart("Hello", "World", 99.00));*/
List partsList;
partsList.push_front(new CarPart("FL2016", "Oil Filter", 18.95));
partsList.push_front(new CarPart("RS12YC", "Spark Plug", 4.15));
partsList.push_front(new CarPart("D5941", "Digital Tire Guage", 12.15));
partsList.push_back(new CarPart("G19216", "Car Wash Solution", 8.15));
partsList.display();
cout << "now we are going to remove the first item in the list" << endl;
system("PAUSE");
partsList.pop_front();
partsList.display();
system("PAUSE");
cout << "now we are going to remove the LAST item from the list" << endl;
partsList.pop_back();
partsList.display();
system("PAUSE");
return 0;
}
List.h
#pragma once
#include "node.h"
class List
{
private:
int listSize;
Node* n;
Node* temp;
Node* head;
Node* tail;
public:
List();
void push_front(CarPart*);
void push_back(CarPart*);
void pop_front();
void pop_back();
void display();
~List();
};
List.cpp
#include "stdafx.h"
#include "List.h"
List::List()
{
}
void List::display()
{
Node* test = head;
for (int i = 0; i < listSize; i++) {
cout << test;
}
}
Node.h
#pragma once
#include "CarPart.h"
class Node
{
private:
CarPart* data;
Node* next;
Node* previous;
public:
Node();
CarPart* getData();
void setData(CarPart*);
void setNext(Node*);
void setPrevious(Node*);
Node* getPrevious();
Node* getNext();
void display();
~Node();
};
Node.cpp
#include "stdafx.h"
#include "Node.h"
Node::Node()
{
}
void Node::display()
{
cout << data;
}
CarPart.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class CarPart
{
private:
string partNumber;
string description;
double price;
public:
CarPart();
CarPart(string, string, double);
string getPartNumber();
string getDescription();
double getPrice();
void display();
~CarPart();
friend ostream& operator<<(ostream& os, CarPart* dt);
};
CarPart.cpp
#include "stdafx.h"
#include "CarPart.h"
CarPart::CarPart()
{
}
CarPart::CarPart(string n, string d, double p)
{
partNumber = n;
description = d;
price = p;
}
string CarPart::getPartNumber()
{
return partNumber;
}
string CarPart::getDescription()
{
return description;
}
double CarPart::getPrice()
{
return price;
}
ostream& operator<<(ostream& os, CarPart* dt)
{
os << dt->getPartNumber() << endl << dt->getDescription() << endl << dt->getPrice() << endl;
return os;
}
There are multiple problems with your code, but they all share the same root problem, so I'll just explain the first one, and after figuring out how to fix it you should be able to fix the rest of them by yourself:
void List::display()
{
Node* test = head;
for (int i = 0; i < listSize; i++) {
cout << test;
}
}
As you've observed, all this does is print the value of the pointer. Examining the contents of your header files, it appears that your class Node has a method called display().
You did now show the display() method, but given what I see in List::display(), it's reasonable to expect that Node::display()'s purpose would be similar, so you probably meant to do this, instead:
void List::display()
{
Node* test = head;
for (int i = 0; i < listSize; i++) {
test->display();
}
}
But this is not right, either. All this will accomplish is invoke your head Node's display() method over and over again. If your List has five Nodes, you'll get the contents of the first Node display()ed five times. You simply need to change this loop to walk through the link list, instead.
Now, your Node::display() method has the same problem as above, but now you should be able to fix it yourself.

Linked list program facing segmentation fault

I was writing a C++ program to implement a linked list. On compilation it's not giving any error but in the output windows it goes blank and program ended with
list1.exe has
encountered a problem and needs to close.
Debugger response: Program received signal SIGSEGV, Segmentation fault.
Maybe it's because of memory leakage, but I'm not able to figure out the exact bug and how can we fix that. Please what's wrong in the prog and what should be fixed?
Below is the code
//Program to implement linked list
#include <iostream>
#include <cstdlib>
using namespace std;
class Node
{
int data;
Node * next;
public:
Node (){}
int getdata(){return data ;}
void setdata(int a){data=a;}
void setnext(Node* c){next=c;}
Node* getnext(){return next;}
};
class linkedlist
{
Node* head;
public:
linkedlist(){head=NULL;}
void print ();
void push_back(int data);
};
void linkedlist::push_back(int data)
{
Node* newnode= new Node();
if(newnode!=NULL)
{
newnode->setdata(data);
newnode->setnext(NULL);
}
Node* ptr= head;
if(ptr==NULL)
{head=newnode;}
while ((ptr->getnext())!=NULL)
{
ptr=ptr->getnext();
}
ptr->setnext(newnode);
}
void linkedlist::print()
{
Node* ptr=head;
if(ptr==NULL)
{cout<<"null"; return;}
while(ptr!=NULL)
{
cout<<(ptr->getdata())<<" ";
ptr=ptr->getnext();
}
}
int main()
{
linkedlist list;
list.push_back(30);
list.push_back(35);
list.print();
return 0;
}
The main issue is here:
if(ptr==NULL) {head=newnode;}
while ((ptr->getnext())!=NULL)
{
ptr=ptr->getnext();
}
ptr->setnext(newnode);
There's probably meant to be a return; in the if (ptr == NULL) part; as it stands, it sets head = newnode, but then continues to try to access ptr->getnext(), which causes the segfault.
Some answers have suggested setting ptr = head = newnode, but note that the bottom line is ptr->setnext(newnode)—this would cause head->getnext() == head. Infinite list!
For your interest, here's your code:
Formatted nice;
Cleaned up not to use using namespace std; (see the C++ FAQ on this);
Takes advantage of const-correctness;
etc.
Enjoy!
#include <iostream>
#include <stdexcept>
class Node {
int data;
Node *next;
public:
Node(): next(NULL) {}
int getdata() const {
return data;
}
void setdata(int a) {
data = a;
}
Node *getnext() const {
return next;
}
void setnext(Node *c) {
next = c;
}
};
class linkedlist {
Node* head;
public:
linkedlist(): head(NULL) {}
void print() const {
Node *ptr = head;
if (ptr == NULL) {
std::cout << "null";
return;
}
while (ptr != NULL) {
std::cout << ptr->getdata() << " ";
ptr = ptr->getnext();
}
}
void push_back(int data) {
Node *newnode = new Node();
if (newnode == NULL) {
throw std::runtime_error("out of memory!");
}
newnode->setdata(data);
Node *ptr = head;
if (ptr == NULL) {
head = newnode;
return;
}
while ((ptr->getnext()) != NULL) {
ptr = ptr->getnext();
}
ptr->setnext(newnode);
}
};
int main() {
linkedlist list;
list.push_back(30);
list.push_back(35);
list.print();
return 0;
}
In the following line: while ((ptr->getnext())!=NULL) ptr is NULL
The push_back code is incorrect, and I've seen some other parts of your code that can be improved:
#include <iostream>
#include<cstdlib>
using namespace std;
class Node
{
int data;
Node * next;
public:
Node(int d = 0) : data(d), next(NULL) {}
int getdata() { return data; }
void setdata(int a) { data = a; }
void setnext(Node* c) { next = c; }
Node* getnext() { return next; }
};
class linkedlist
{
Node* head;
public:
linkedlist() : head(NULL) {}
void print ();
void push_back(int data);
};
void linkedlist::push_back(int data)
{
Node* newnode = new Node(data);
if(head == NULL)
{
head = newnode;
}
else
{
Node* last = head;
while(last->getnext() != NULL)
last = last->getnext();
last->setnext(newnode);
}
}
void linkedlist::print()
{
Node* ptr = head;
if(!ptr)
{
cout << "null";
return;
}
while(ptr != NULL)
{
cout << ptr->getdata() << " ";
ptr=ptr->getnext();
}
}
int main()
{
linkedlist list;
list.push_back(30);
list.push_back(35);
list.print();
return 0;
}
There are still some points to be improved...