c++ operator == overloading in linked list - c++

I'm wondering why my overloaded == function is not working. I'm confused about the private head. Would the private head be the head of the linked list that was made last? So if I compared the last linked list with the inputted LinkedList then wouldn't it work?
code for append
void LL::append(string pName,string phone)
{
Node *newNode = new Node;
newNode->name = pName;
newNode->phoneNumber = phone;
newNode->next = nullptr;
if (head == nullptr)
{
head = newNode;
}
else
{
Node *nodePtr = head;
while (nodePtr->next != nullptr)
{
nodePtr = nodePtr->next;
}
nodePtr->next = newNode;
}
}
code for deep copy
LL::LL(const LL& source)
{
head = nullptr;
Node *nodePtr = source.head;
while(nodePtr)
{
append(nodePtr->name,nodePtr->phoneNumber);
nodePtr = nodePtr->next;
}
}
main.cpp
#include <iostream>
#include "node.h"
using namespace std;
int main()
{
LL list;
list.append("jack","2");
list.append("jack2","1");
list.append("jack3","3");
list.append("jack4","4");
list.insertatBegin("notjack","0");
list.print();
list.searchByName("jack");
cout << "cloning------------------" <<endl;
LL list2(list);
//list.destroy();
//list2.append("jack","223");
list2.print();
if(list == list2)
{
cout << "same" <<endl;
}
else
{
cout << "not same" <<endl;
}
}
.h file
#ifndef NODE_H
#define NODE_H
#include <iostream>
using namespace std;
class Node
{
public:
string name; //data
string phoneNumber;
Node* next; //pointer to next
};
class LL
{
private:
Node* head; // list header
public:
LL();
~LL();
LL(const LL& source);
void append(string pName,string phone);
void insertatBegin(string pName,string phone);
void searchByName(string pName);
void print();
void destroy();
bool operator== (const LL& L1);
};
#endif
cpp file for class functions
bool LL::operator == (const LL &L1)
{
bool status = true;
Node *nodePtr = L1.head;
Node *nodePtr2 = head;
//cout << tmp.head <<endl;
while (nodePtr != nullptr)
{
if (nodePtr == nodePtr2)
{
nodePtr = nodePtr->next;
nodePtr2 = nodePtr2->next;
}
else
{
status = false;
}
}
return status;
}

I do not know what is your implementation of Copy Constructor if it is working fine then this should work.
bool LL::operator==(const LL& L1) const{
if (&L1==this){
return true;
}
else{
Node* current = L1.head;
Node* lhs = this->head;
while(current != nullptr){
if(current->name != lhs->name || current->phoneNumber != lhs->phoneNumber)
return false;
current = current->next;
lhs = lhs->next;
}
return true;
}}

Related

C++ Linked list only print the first 3 nodes

When you run the code, it won't print anything unless when you run it with 3 appends. Why is that? Inside the code, I added cout statement to check if it ran and when I appended 4 things to the linked list, it only ran once in the append function. But when I ran it with only 3 things appended to the list, it displayed the cout statement 3x.
main.cpp:
#include <iostream>
#include "node.h"
using namespace std;
int main()
{
LL list;
list.append("jack","2");
list.append("jack","1");
list.append("jack","3");
list.append("jack","4");
//list.insertatBegin("notjack","0");
list.print();
}
node.cpp:
#include <iostream>
using namespace std;
#include "node.h"
LL::LL()
{
head = nullptr;
}
void LL::append(string pName,string phone)
{
Node *nodePtr;
if (head == nullptr)
{
head = new Node;
head->name = pName;
head->phoneNumber = phone;
head->next = nullptr;
}
else
{
nodePtr = head;
while(nodePtr->next !=nullptr)
{
nodePtr = nodePtr->next;
}
nodePtr->next = new Node;
nodePtr->next->name = pName;
nodePtr->next->phoneNumber = phone;
nodePtr->next->next = nullptr;
}
}
void LL::print()
{
//cout << "ran" <<endl;
Node *nodePtr;
nodePtr = head;
while (nodePtr == nullptr)
{
cout << nodePtr ->name << " " << nodePtr->phoneNumber <<endl;
nodePtr = nodePtr->next;
}
}
node.h:
#ifndef NODE_H
#define NODE_H
#include <iostream>
using namespace std;
class Node
{
public:
string name; //data
string phoneNumber;
Node* next; //pointer to next
};
class LL
{
private:
Node* head; // list header
public:
LL();
void append(string pName,string phone);
void insertatBegin(string pName,string phone);
void print();
};
#endif
There are 2 problems with your code:
append() has undefined behavior, because newNode is uninitialized. Its value is indeterminate, causing it to point at random memory. You are not pointing it to a valid new'ed instance of Node before trying to populate it.
print() is not looping through the list at all.
Try this:
void LL::append(string pName,string phone)
{
Node *newNode = new Node; // <-- notice 'new'!
// these assignments really should be handled by a constructor...
newNode->name = pName;
newNode->phoneNumber = phone;
newNode->next = nullptr;
if (head == nullptr)
// better: if (!head)
{
cout << "it ran" <<endl;
head = newNode;
}
else
{
cout << "it ran2" <<endl;
Node *nodePtr = head;
while (nodePtr->next != nullptr)
// better: while (nodePtr->next)
{
nodePtr = nodePtr->next;
}
nodePtr->next = newNode;
}
}
void LL::print()
{
//cout << "ran" <<endl;
Node *nodePtr = head;
while (nodePtr != nullptr) // <-- '!=', not '=='
// better: while (nodePtr)
{
cout << nodePtr ->name << " " << nodePtr->phoneNumber << endl;
nodePtr = nodePtr->next;
}
}
That said, append() can be simplified a bit more:
class Node
{
public:
string name; //data
string phoneNumber;
Node* next = nullptr; //pointer to next
Node(string pName, string phone) : name(pName), phoneNumber(phone) {}
};
void LL::append(string pName,string phone)
{
Node *newNode = new Node(pName, phone);
Node **nodePtr = &head;
while (*nodePtr)
{
nodePtr = &((*nodePtr)->next);
}
*nodePtr = newNode;
// Alternatively:
/*
Node **nodePtr = &head;
while (*nodePtr)
{
nodePtr = &((*nodePtr)->next);
}
*nodePtr = new Node(pName, phone);
*/
}
For starters your newNode pointer does not point to anything and you are assigning to uninitialized variables name, phonenumber and next.
Node *nodePtr;
newNode->name = pName;
newNode->phoneNumber = phone;
newNode->next = nullptr;

Sorting a linked list with multiple parameters

I am wanting to insert nodes according to their location year and month. So basically all locations are clumped together and then they are sorted according to the year and the months. Below is the code in my linkedlist.cpp file. My insert function I believe is the main cause of my issues. When I use the overload operator to print the list and then the copied list, it is only printing one of the inserted nodes.
#include <iostream>
#include <string>
#include <vector>
#include "linkedlist.h"
using namespace std;
LinkedList::LinkedList() : head(nullptr), tail(nullptr){
// Implement this function
}
LinkedList::~LinkedList() {
// Implement this function
this->clear();
}
LinkedList::LinkedList(const LinkedList& source) {
// Implement this function
head = nullptr;
tail = nullptr;
Node* tempNode = source.head;
while(tempNode != nullptr) {
insert(tempNode->loc, tempNode->yr, tempNode->mo, tempNode->temp);
tempNode = tempNode->next;
}
}
LinkedList& LinkedList::operator=(const LinkedList& source) {
if (this != &source) {
this->clear();
Node* tempNode = source.head;
while(tempNode != nullptr){
insert(tempNode->loc, tempNode->yr, tempNode->mo, tempNode->temp);
tempNode = tempNode->next;
}
}
return *this;
}
void LinkedList::insert(int location, int year, int month, double temperature) {
// Implement this function
Node* newNode = new Node();
newNode->loc = location;
newNode->yr = year;
newNode->mo = month;
newNode->temp = temperature;
Node* tempNode = head;
if(tail == nullptr & head == nullptr){
newNode = head;
}
while(tempNode != nullptr){
if((tempNode->loc == newNode->loc) && (tempNode->yr == newNode->yr)){
if(tempNode->mo > newNode->mo){
newNode->next = tempNode->next;
tempNode->next = newNode;
}
if(tempNode->mo < newNode->mo){
newNode->next = tempNode;
}
}
if(tempNode->loc > newNode->loc){
newNode->next = tempNode->next;
tempNode->next = newNode;
}
if(tempNode->loc < newNode->loc){
newNode->next = tempNode->next;
tempNode->next = newNode;
}
tempNode = tempNode->next;
}
}
void LinkedList::clear() {
// Implement this function
Node* current = head;
while (current != nullptr) {
Node* deleteNode = current;
current = current->next;
delete deleteNode;
}
head = nullptr;
tail = nullptr;
}
void LinkedList::print() const {
/* Do not modify this function */
print(cout);
}
void LinkedList::print(ostream& os) const {
/* Do not modify this function */
os << *this;
}
ostream& operator<<(ostream& os, const LinkedList& ll) {
// Implement this function
Node* tempNode = ll.head;
if (tempNode == nullptr) {
os << " <Empty List>";
}
while (tempNode != nullptr) {
if (tempNode != ll.head)
cout << " " << tempNode->loc << " " << tempNode->yr << " " << tempNode->mo << " " << tempNode->temp << endl;
}
tempNode = tempNode->next;
return os;
}

C++ RemoveFront function for Doubly Linked List

I'm working on a lab for school and I'm stuck on a function for a doubly linked list. When I try to remove the front node from the list with the removeFront() function it returns NULL and couts for me to create a list even though there already is one. I'll post my cpp file and main below and hopefully someone can help me understand what's going wrong with it.
//DLinkedList.h
#pragma once
#include <string>
using namespace std;
typedef string Elem;
struct DNode
{
Elem value;
DNode* next;
DNode* prev;
};
class DLinkedList
{
public:
DLinkedList() { header_ = NULL; }
~DLinkedList() { };
bool empty() const;
const Elem& front() const;
const Elem& back() const;
void addFront(const Elem& e);
void addBack(const Elem& e);
void removeFront();
void removeBack();
private:
DNode* header_;
DNode* trailer_;
protected:
void add(DNode* v, const DNode& e);
void remove(DNode* v);
};
//DLinkedList.cpp
#include <iostream>
#include "DLinkedList.h"
using namespace std;
const Elem& DLinkedList::front() const
{
if (header_ == NULL)
{
cout << "Please create a doubly linked list first.\n\n";
}
else
{
return header_->value;
}
}
void DLinkedList::addFront(const Elem& e) //DONE
{
// If there is no header
// create a temporary node and set
// the header to it
if (header_ == NULL)
{
DNode *temp;
temp = new(struct DNode);
temp->prev = NULL;
temp->value = e;
temp->next = NULL;
header_ = temp;
trailer_ = temp;
}
else
{
//Create current node to point to header
// and temp node to be the new front node
DNode *current;
DNode *temp;
current = header_;
temp = new(struct DNode);
temp->prev = NULL;
temp->value = e;
temp->next = current->next;
header_->prev = temp->next;
header_ = temp;
}
cout << "Element Inserted at the front." << endl;
}
void DLinkedList::removeFront()
{
// Check to see if there is anything
// in the list first
if (header_ == NULL)
{
cout << "Create a doubly linked list first.";
}
// Check to see if the list has more than one item.
// If it only has one node erase it.
DNode *current;
current = header_;
if (current->next == NULL)
{
header_->next = NULL;
header_->value = "";
header_->prev = NULL;
header_ = NULL;
}
else
{
current = current->next;
//header_->next = NULL;
//header_->value = "";
//header_->prev = NULL;
header_ = current;
header_->prev = NULL;
}
}
//Main.cpp
#include <iostream>
#include <string>
#include <cassert>
#include "DLinkedList.h"
using namespace std;
int main()
{
DLinkedList album;
album.addFront("Word");
album.addFront("Turn");
album.addFront("Bird");
album.addFront("Weird");
cout << album.front() << endl;
album.removeFront();
cout << album.front() << endl;
system("pause");
return 0;
}
This how i would do it.
void DLinkedList::removeFront()
{
// Check to see if there is anything
// in the list first
if (header_ == NULL)
{
cout << "Create a doubly linked list first.";
}
// Check to see if the list has more than one item.
// If it only has one node erase it.
if (header_->next == NULL)
{
delete header_;
}
else
{
DNode* next = header_->next;
delete header_;
header_ = next;
header_->prev = NULL;
}
}
I think your addFront is also wrong, i would do it like that:
void DLinkedList::addFront(const Elem& content) //DONE
{
// If there is no header
// create a temporary node and set
// the header to it
if (header_ == NULL)
{
header_ = new(struct DNode);
header_->prev = NULL;
header_->value = content;
header_->next = NULL;
trailer_ = header_;
}
else
{
//Create current node to point to header
// and temp node to be the new front node
DNode *tmp;
tmp = new(struct DNode);
tmp->prev = NULL;
tmp->value = content;
tmp->next = header_;
header_->prev = tmp;
header_ = tmp;
}
cout << "Element Inserted at the front." << endl;
}

.exe has stopped working code blocks cpp

`Hello
I just wrote this code in Code Blocks and after building and running , it says that the programm has stopped working. I can't find what I have done wrong. I don't know if the problem is related to my code or is something that has to do with the compiler I am using or something else.
Please help
Library.h:
#ifndef LIBRARY_H
#define LIBRARY_H
#include <iostream>
#include <string>
using namespace std;
class Library
{
public:
struct book
{
string tittle;
int number;
struct book* next;
}* head, *tail, *ptr;
Library();
~Library();
book* searchName(book *, string);
void addNode(book *);
book *initNode(string s, int i);
void displayNode(book *ptr) const;
void displayList(book *ptr) const;
protected:
};
#endif
Library.cpp
#include "Library.h"
Library::Library() :
head(NULL), tail(NULL)
{
}
Library::~Library()
{
book *current, *temp;
current = head;
temp = head;
while (current != NULL)
{
current = current->next;
delete temp;
temp = current;
}
}
Library::book * Library::searchName(Library::book* ptr, string name)
{
while (name != ptr->tittle)
{
ptr = ptr->next;
if (ptr == NULL)
break;
}
return ptr;
}
void Library::addNode(book *newNode)
{
if (head == NULL)
{
head = newNode;
head = newNode;
}
tail->next = newNode;
newNode->next = NULL;
tail = newNode;
}
Library::book *Library::initNode(string s, int i)
{
book *ptr = new book;
if (ptr == NULL)
return static_cast<book *>(NULL);
else
{
ptr->tittle = s;
ptr->number = i;
return ptr;
}
}
void Library::displayNode(book *ptr) const
{
cout << ptr->number << ": " << ptr->tittle << endl;
}
void Library::displayList(book *ptr) const
{
if (!ptr)
cout << "Nothing to display" << endl;
while (ptr)
{
displayNode(ptr);
ptr = ptr->next;
}
}
main.cpp
#include "Library.h"
#include <iostream>
using namespace std;
int main()
{
Library a;
Library::book *ptrr;
ptrr = a.initNode("s1", 1);
a.addNode(ptrr);
ptrr = a.initNode("s2", 2);
a.addNode(ptrr);
a.displayList(a.head);
}
When you call the first a.addNode(ptrr) from main it does tail->next = newNode; (within Library::addNode), but, as tail is NULL (not assigned yet), it crashs....
Now, there could be other problems in the code, but this is most likely the first one that will make the program stop working...
Note that some stuff in your code could be simplified.
Like:
Library::book *Library::initNode(string s, int i)
{
book *ptr = new book;
if (ptr == NULL)
return static_cast<book *>(NULL);
else
{
ptr->tittle = s;
ptr->number = i;
return ptr;
}
}
could simply be:
Library::book *Library::initNode(string s, int i)
{
book *ptr = new book;
if (ptr != NULL)
{
ptr->tittle = s;
ptr->number = i;
}
return ptr;
}
And:
void Library::addNode(book *newNode)
{
if (head == NULL)
{
head = newNode;
head = newNode;
}
tail->next = newNode;
newNode->next = NULL;
tail = newNode;
}
Should be:
void Library::addNode(book *newNode)
{
if ( newNode != NULL ) // just in case
{
if (head == NULL)
{
head = newNode; // one is enough
}
if ( tail != NULL ) // to fix your crash
tail->next = newNode;
newNode->next = NULL;
tail = newNode;
}
}
Also, see user4581301 comment, the destructor code does not even compile....

<LinkedList> Program doesn't give the correct answer

this is my lab and I work all of it. After long time of debugging, fixing errors, finally it can compile. But when it run, it didn't give me the correct answer. It just kept saying : did not find y (may be x was added) and it was 4 line with the same answer.
please look at my code and tell me why it didn't work.
Thanks a lot.
Here is my code:
LinkedList.h:
#ifndef _LINKED_LIST_
#define _LINKED_LIST_
#include <ostream>
class LinkedList
{
public:
LinkedList();
LinkedList(char ch);
LinkedList(const LinkedList& List);
~LinkedList();
void add(const char& ch);
bool find(char ch);
bool del(char ch);
friend std::ostream& operator<<(std::ostream& out, LinkedList& list);
private:
struct node
{
char item;
node * next;
};
node * head;
int size;
};
#endif // _LINKED_LIST_
Linkedlist.cpp
#include "linkedlist.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <cstring>
using namespace std;
LinkedList::LinkedList() : head(NULL)
{
}
LinkedList::LinkedList(char ch):head(NULL)
{
char currData;
currData = ch;
add(currData);
}
LinkedList::~LinkedList()
{
node * curr = head;
while(head)
{
curr = head->next;
delete head;
head = curr;
}
}
LinkedList::LinkedList(const LinkedList& List)
{
if(List.head == NULL)
head = NULL;
else
{
//copy first node
head = new node;
assert(head != NULL);
head->item = List.head->item;
//copy the rest of the list
node * destNode = head; //points to the last node in new list
node * srcNode = List.head->next; //points to node in aList
while(srcNode != NULL) //or while (srcNode)
{
destNode->next = new node;
assert(destNode->next != NULL); //check allocation
destNode = destNode->next;
destNode->item = srcNode->item;
srcNode = srcNode->next;
}
destNode->next = NULL;
}
}
ostream& operator<<(std::ostream& out, LinkedList& list)
{
while(list.head)
{
out << list.head->item << endl;
list.head = list.head->next;
}
return out;
}
void LinkedList::add(const char& ch)
{
node * prev = NULL;
node * curr = head;
while (curr != NULL && curr->item < ch)
{
prev = curr;
curr = curr->next;
}
if (curr && curr->item != ch)
{
node * newNode = new node;
newNode->item = ch;
newNode->next = NULL;
newNode->next = curr;
if (prev == NULL)
head = newNode;
else
prev->next = newNode;
size++;
}
}
bool LinkedList::del(char ch)
{
char a;
node * prev = NULL;
node * curr = head;
while (curr)
{
a = curr->item;
if ( a == ch)
{
if(!prev)
head = curr->next;
else
prev->next = curr->next;
delete curr;
size--;
return true;
}
prev = curr;
curr = curr->next;
}
return false;
}
bool LinkedList::find(char ch)
{
char a;
node * prev = NULL;
node * curr = head;
while (curr)
{
a = curr->item;
if ( a == ch)
{
return true;
}
prev = curr;
curr = curr->next;
}
return false;
}
app.cpp
#include <iostream>
#include "linkedlist.h"
using namespace std;
void find(LinkedList& list, char ch)
{
if (list.find(ch))
cout << "found ";
else
cout << "did not find ";
cout << ch << endl;
}
int main()
{
LinkedList list;
list.add('x');
list.add('y');
list.add('z');
cout << list;
find(list, 'y');
list.del('y');
cout << list;
find(list, 'y');
list.del('x');
cout << list;
find(list, 'y');
list.del('z');
cout << list;
find(list, 'y');
return 0;
}
Your add method doesn't work, if the item to insert goes at the end it is not inserted (because you are checking for curr == NULL before inserting). Since head is set to NULL when you create the list if(curr && ...) won't ever be true and no item will be inserted.