When trying to add a new Node to the liked list it gives me a Segmentation fault. Can someone tell me what is wrong in the implementation of the addBook() function. I am not sure if it's the implementation of the function that is wrong, or the way that I've declared the classes.
class Reservation {
public:
int getID();
string getResevNum();
void setId(int x);
void setReseNum(string y);
private:
int ID;
string reservedNumber;
};
class ReservationCollection {
public:
ReservationCollection();
~ReservationCollection();
int getUserId(int &id);
string getUserBook(string &bookCall);
void findReservation();
void display();
void addBook(int id, string book);
void RemoveBook();
void ShutDown();
private:
struct Node {
Reservation *data;
Node *next;
};
Node *head;
};
ReservationCollection::ReservationCollection() {
Node *head = new Node;
head->next = NULL;
}
ReservationCollection::~ReservationCollection() {
}
void ReservationCollection::addBook(int id, string book){
Node *tmp = new Node;
tmp->data->setId(id);
tmp->data->setReseNum(book);
tmp->next = head->next;
head->next = tmp;
cout <<"Good\n";
}
int Reservation::getID(){
return ID;
}
string Reservation::getResevNum(){
return reservedNumber;
}
void Reservation::setId(int x){
ID = x;
}
void Reservation::setReseNum(string y){
reservedNumber = y;
}
int ReservationCollection::getUserId(int &id){
cout << "Enter Id number " << endl;
cin >> id;
return id;
}
string ReservationCollection::getUserBook(string &bookCall){
cout << "Enter book reservatin " << endl;
cin >> bookCall;
return bookCall;
}
int main()
{
int ID;
string BookNum;
char cmd;
do {
cout << "Enter command: ";
cin >> cmd;
ReservationCollection list;
if (cmd == 'A' || cmd == 'a'){
list.getUserId(ID);
list.getUserBook(BookNum);
list.addBook(ID, BookNum);
}
else if (cmd == 'S' || cmd == 's'){
cout << " list";
}
} while (cmd != 'Q' || cmd == 'q');
}
Wish I could just comment this:
All instances of the line Node *tmp = new Node; should read Node *tmp = new Node();
Don't use pointers if you don't have to. In this example Node has to be a pointer, because the list may have zero nodes, or 1000 nodes, so we need pointers to dynamically allocate memory on demand.
But (Reservation)data does not have to be a pointer. Each node always has one Reservation member.
If you do declare it as pointer then you must allocate it, and free it when it is no longer needed.
head should be initialized to NULL, because the single linked-list has no nodes when it is initialized. The first node inserted becomes the head.
#include <iostream>
#include <string>
using namespace std;
class Reservation
{
private:
int ID;
string reservedNumber;
public:
int getID() { return ID; }
string getResevNum() { return reservedNumber; }
void setId(int x) { ID = x; }
void setReseNum(string y) { reservedNumber = y; }
};
class ReservationCollection
{
public:
struct Node
{
Reservation data;
Node *next;
};
ReservationCollection();
~ReservationCollection();
void addBook(int id, string book);
Node* getHead() { return head; }
private:
Node *head;
};
ReservationCollection::ReservationCollection()
{
head = NULL;
}
ReservationCollection::~ReservationCollection()
{
Node *p = head;
while (p)
{
Node *next = p->next;
cout << "delete: " << p->data.getID() << ", " << p->data.getResevNum() << endl;
delete p;
p = next;
}
}
void ReservationCollection::addBook(int id, string book)
{
Node *node = new Node;
node->data.setId(id);
node->data.setReseNum(book);
//this element is the last element
node->next = NULL;
if (!head)
{
//first element inserted
head = node;
head->next = NULL;
}
else
{
//find the previous node in the list
Node *prev = head;
while (prev->next)
prev = prev->next;
//this node is after previous node
prev->next = node;
}
cout << "Good\n";
}
int main()
{
ReservationCollection list;
list.addBook(0, "Book0");
list.addBook(1, "Book1");
list.addBook(2, "Book2");
list.addBook(3, "Book3");
ReservationCollection::Node *p = list.getHead();
while (p)
{
ReservationCollection::Node *next = p->next;
cout << p->data.getID() << ", " << p->data.getResevNum() << endl;
p = next;
}
}
Creating a Node wont create the structure that Reservation *data; tries to point to, and so you try to access non initialized memory.
You need to initialize data:
tmp->data = new Reservation();
Related
I'm trying to add data to a binary tree, however when I run a method that prints the data of the binarytree in order, nothing prints, and the program exits when it should be printing. I've tested it to see if data is actually being added by having the name and weight values of the rootNode print themselves inside the add method everytime its called, but I cannot get the same results inside of the inOrder method. I believe my issue has something to do with the node being passed.
#include <iostream>
using namespace std;
struct node {
int weight;
string name;
node *left, *right;
};
struct node* newNode(int dataw, string datan)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->weight = dataw;
node->name = datan;
node->left = NULL;
node->right = NULL;
return (node);
}
void add(node *rootNode, int dataw, string datan)
{
int lowest_weight;
if (rootNode == NULL )
{
rootNode = newNode(dataw,datan);
lowest_weight = dataw;
}
else
{
if (datan < rootNode->name)
{
if (rootNode->left == NULL)
{
rootNode->left = newNode(dataw,datan);
}
else
{
add(rootNode->left,dataw,datan);
}
}
else
{
if (rootNode->right == NULL)
{
rootNode->right = newNode(dataw,datan);
}
else
{
add(rootNode->right, dataw, datan);
}
}
}
}
void inOrder(node *next)
{
if (next!=NULL)
{
inOrder(next->left);
cout << next->name << " " << next->weight << endl;
inOrder(next->right);
}
}
int main()
{
node *rootNode = NULL;
int height {}, leaves {}, weight {};
string name;
do
{
cout << "Enter name: ";
cin >> name;
if (name == "-1")
break;
cout << "Enter weight: ";
cin >> weight;
add(rootNode, weight, name);
} while (name!="-1");
inOrder(rootNode);
return 0;
}
Resolved it, had to assign the rootNode declaration to a new node method call so the data is not always NULL
node *rootNode = newNode(weight,name);
I have a member class, where I want to delete a node using id. I have created a struct for the linked list. all other functions are working properly, but I cannot delete the node at the given position. It works fine when i add member and when i show it, but when it comes to deleting node it does not work.
#include <iostream>
#include <string>
class member {
public:
struct nodetype {
int id;
string name;
string password;
string type;
nodetype* next;
};
member() {
start = NULL;
}
void addMember(int x, string n, string p, string t) {
nodetype* temp = new nodetype();
temp->id = x;
temp->name = n;
temp->password = p;
temp->type = t;
temp->next = start;
start = temp;
}
void showMember()
{
nodetype* temp = start;
while (temp != NULL)
{
cout << temp->id << "\t" << temp->name << "\t" << temp->type << "\t" << temp->password << endl;
temp = temp->next;
}
}
void deleteMember(int x)
{
nodetype* tmp = start;
while (tmp != NULL)
{
if (tmp->id == x)
{
nodetype* del = tmp;
start->next = tmp->next;
delete del;
}
}
}
private:
nodetype* start;
};
int main()
{
member obj;
obj.addMember(1,"joe","123","student");
obj.addMember(2,"john","456","staff");
obj.deleteMember(2);
obj.showMember();
}
First of all in deleteMember functionyou are not moving tmp forward.You can do it like-
void deleteMember(int x)
{
nodetype* tmp = start;
nodetype* prv = NULL;
while (tmp != NULL)
{
if (tmp->id == x)
{
if(prv != NULL)
{
prv->next=tmp->next;
}
else
{
start=tmp->next;
}
delete tmp;
break;
}
prv=tmp;
tmp=tmp->next;
}
}
Whats wrong with this code?
I am writing this code to implement singly linked list using arrays but its not working. Im using code::blocks and its crashing on run time. Please help.
I must have missed out on something when it was taught in the class. xD
#include<iostream>
#include<stdio.h>
using namespace std;
class Node
{
int data;
Node *next;
public:
Node(int n)
{
data=n;
next=NULL;
}
friend class List;
};
class List
{
Node *listptr;
public:
void create();
void display();
};
void List::create()
{
Node *temp;
int n, num;
cout << "Enter number of nodes:" << endl;
cin >> n;
cout << "/nEnter the data" << endl;
for(int i=0; i<n; i++)
{
cin >> num;
Node *new_node=new Node(num);
if(listptr==NULL)
listptr=temp=new_node;
else
{
temp->next=new_node;
temp=temp->next;
}
}
}
void List::display()
{
Node *temp=listptr;
while(temp!=NULL)
{
cout << temp->data << "->";
temp=temp->next;
}
}
main()
{
List l1;
l1.create();
l1.display();
}
listptr not initialized, you can initialize in constructor.
List() {
listptr = 0;
}
Class List should be
class List
{
Node *listptr;
public:
List() {
listptr = 0;
}
void create();
void display();
};
Try following piece of code -
First Creating Node
class ListElement
{
int data;
ListElement* next;
public:
void set_element(int item) { data = item; }
int get_value() { return data; }
friend class List;
};
Another class for further operation
class List
{
ListElement *Start, *Tail, *New;
public:
List() { Start = Tail = New = NULL; } // initialise all pointer value to NULL
void add_element(int element) {
// Create a new Node
New = new ListElement;
New->set_element(element);
New->next = NULL;
// adding value or linkig each node to each other
(Start == NULL) ? Start = New : Tail->next = New;
Tail = New;
}
// print the whole linked list
void print()
{
ListElement* Current = Start;
while (Current != NULL)
{
cout << Current->get_value() << endl;
Current = Current->next;
}
}
};
Main Function
int main()
{
List L;
int num_of_element, element;
cin >> num_of_element;
for (int i(0); i < num_of_element; i++) {
cin >> element;
L.add_element(element);
}
L.print();
}
Hope it'll work.
The purpose of my program is to read in data from a file and build a linked list with this data and then deallocate all the nodes used.
the program also needs to print out the address of nodes after they are created and then after that they are deleted
#include <iostream>
#include <string>
#include <fstream>
#include "BigHero.h"
using namespace std;
// Linked List Struct
struct Node{
BigHero data;
Node* Next;
};
// Funtion Prototypes
int countHeros(string,int&);
void createList(BigHero,int,Node*&,Node*&,Node*&);
void printList(Node*,Node*,Node*);
void deallocateList(Node*&,Node*&,Node*&);
int main()
{
// Program Variables
Node* head;
Node* currentPtr;
Node* newNodePtr;
string Filename = "ola5party.dat"; // File string varible
int charNumber = 0; // variable to hold number of Heroes
int i = 0; // Loop control varible
countHeros(Filename,charNumber); // Function call used to count number of Heros
ifstream inFile;
inFile.open(Filename.c_str());
if(!inFile){
cout << "Error in opening file" << endl;
return 0;
}
BigHero Hero;
while(inFile)
{
inFile >> Hero;
createList(Hero,charNumber,head,currentPtr,newNodePtr);
}
printList(head,currentPtr,newNodePtr);
deallocateList(head,currentPtr,newNodePtr);
inFile.close();
return 0;
}
int countHeros(string Filename,int& charNumber)
{
ifstream inFile;
inFile.open(Filename.c_str());
string aLineStr;
while (getline(inFile, aLineStr))
{
if (!aLineStr.empty())
charNumber++;
}
inFile.close();
return charNumber;
}
void createList(BigHero Hero, int charNumber,Node*& head, Node*& currentPtr, Node*& newNodePtr)
{
head = new Node;
head->data =Hero;
currentPtr = head;
newNodePtr = new Node;
cout << "Allocated # " << newNodePtr << endl;
newNodePtr->data = Hero;
currentPtr->Next = newNodePtr;
currentPtr = newNodePtr;
}
void printList(Node* head, Node* currentPtr, Node* newNodePtr)
{
if(head != NULL)
{
currentPtr = head;
while(currentPtr->Next != NULL)
{
cout << currentPtr->data << endl;
currentPtr = currentPtr->Next;
}
}
}
void deallocateList(Node*& head ,Node*& currentPtr,Node*& newNodePtr)
{
if( head != NULL)
{
currentPtr = head;
while( head -> Next != NULL)
{
head = head->Next;
cout << "Deleting # " << head << endl;
delete currentPtr;
currentPtr = head;
}
delete head;
head = NULL;
currentPtr = NULL;
}
}
the program like this runs without errors, but here is the problem it will input all the information required but since i only have one variable hero class it is constantly replacing the information.
i tried to make a class array (example hero[i]) but cant seem to get it right and am not even sure if that is the solution. Everything is fine but i cant get the desired number of class object and i always end up with one class
this is my desired output but i only get one class object
Allocated#0x8722178
Allocated#0x87221d0
Allocated#0x8722210
Allocated#0x8722230
Allocated#0x8722288
Allocated#0x87222c8
Hero:MacWarriorLevel134,(34,16,48)Exp:13425
Hero:LinuxMageLevel149,(24,54,21)Exp:14926
Hero:PCBardLevel122,(18,32,17)Exp:12221
Hero:PythonThiefLevel90,(24,18,61)Exp:9001
Hero:CplusPaladinLevel159,(31,38,29)Exp:15925
Deleting#0x8722178
Deleting#0x87221d0
Deleting#0x8722210
Deleting#0x8722230
Deleting#0x8722288
Deleting#0x87222c8
It seems you have misunderstood the basic idea behind a link listed. You are not supposed to overwrite head again and again when adding element. head shall only be changed when the list is empty.
Try something like this:
struct Node
{
BigHero data;
Node* next;
};
void addNewNode(Node*& head, ....)
{
if (head == nullptr)
{
// List empty so add new node as head
head = new Node;
head->next = nullptr;
return;
}
// Find last element in list (performance can be improved with a tail*)
Node* temp = head;
while (temp->next != nullptr) temp = temp->next;
// Add new element to end of list
temp->next = new Node;
temp->next->next = nullptr
return;
}
int main()
{
Node* head = nullptr;
addNewNode(head, ....);
return 0;
}
For performance it is often good to have a tail-pointer also.
Further you should not define head in main() but make a class/struct for it and put the relevant functions in the class. Like:
struct Node
{
BigHero data;
Node* next;
};
class ListOfNode
{
public:
ListOfNode() : head(nullptr), size(0) {}
~ListOfNode()
{
// Delete all nodes
}
void addNewNode(....)
{
// ....
++size;
}
size_t size() { return size; }
private:
Node* head; // Optional: Add a tail* for better performance
size_t size;
};
int main()
{
ListOfNode list;
list.addNewNode(....);
cout << list.size() << endl;
return 0;
}
So I am trying to improve this code in c++. What this does it creates two classes: Student and Studentlist. Any suggestions on improving the linked list data structure here will be greatly appreciated.
#include <iostream>
using namespace std;
//declaring a class student
class Student
{
public:
char *RollNo;
Student *next;
//function student that includes arguments roll number and a pointer poniting to next node student
Student(char *rollNo, Student *Next)
{
this->RollNo = rollNo;
this->next = Next;
}
//fucntion to get roll number
char* getRollNo()
{
return RollNo;
}
//function to get the pointer to next node named student
Student *getNext()
{
return next;
}
void setNext(Student *aNode)
{
this->next = aNode;
}
};
//declareing a class StudentList
class StudentList
{
public:
Student *head;
// default constructor
StudentList()
{
head = NULL;
}
void Add(char *aRollNo)
{
Student *newStudent = new Student(aRollNo, NULL);
Student *temp = head;
if (temp != NULL)
{
while (temp->getNext() != NULL)
{
temp = temp->getNext();
}
temp->setNext(newStudent);
}
else
{
head = newStudent;
}
}
void display()
{
Student *temp = head;
if (temp == NULL)
{
cout << "no student data in the Student List" << endl;
return;
}
if (temp->getNext() == NULL)
{
cout << temp->getRollNo();
}
else
{
do
{
cout << temp->getRollNo() << " --next--> ";
temp = temp->getNext();
} while (temp != NULL);
cout << " end --> null" << endl;
}
}
};
main()
{
StudentList list;
list.Add("My Roll Number is 411\n");
list.display();
cout << "--------------------------------\n";
system("pause");
return 0;
}
The declaration of main() is not complete.
main()
See What is the proper declaration of main?
Also literal strings have a type of char const*. So your method call Add("XXX") has no matching point in the class. The closest you have is Add(char*) which does not match the const part.
Personally I would avoid using C-Strings in C++. You should look at using std::string to handle strings of characters it will avoid many problems.
while you are always add at the last i recomended you to replace your Add algorithm code with this
Student* Add(char *aRollNo,Student* last)
{
Student *newStudent = new Student(aRollNo, NULL);
Student *temp = last;
if (head == NULL){
head=newStudent;
temp=head;}
else
temp=temp->setNext(newStudent);
return temp;
}