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;
}
via new_programmer_22
No comments:
Post a Comment