-
Notifications
You must be signed in to change notification settings - Fork 1
/
LinkedList.h
148 lines (126 loc) · 2.88 KB
/
LinkedList.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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#pragma once
#include <iostream>
#include <stdexcept> // std::runtime_error
#include <sstream>
#include <fstream>
#include <string>
#include <cstdlib>
class Node
{
public:
Node* next = nullptr;
int key;
int object;
~Node(){
delete next;
}
};
class LinkedList
{
public:
int length;
Node* head;
LinkedList();
~LinkedList();
void add(int key, int object);
void print();
int search(int key);
void AddData(std::string filename, int isHeading);
};
LinkedList::LinkedList(){
this->length = 0;
this->head = nullptr;
}
LinkedList::~LinkedList(){
delete head;
std::cout << "LIST DELETED" << std::endl;
}
void LinkedList::add(int key, int object){
Node* node = new Node();
node->key = key;
node->object = object;
node->next = nullptr;
if (this->head == nullptr)
{
this->head = node;
head->next = nullptr;
}
else if(this->head->next == nullptr ){
if (this->head->key >= key)
{
node->next = head;
head = node;
}
else{
head->next = node;
}
}
else{
Node* iter = this->head;
while (iter->next != nullptr && iter->next->key < key)
{
iter = iter->next;
}
if (iter == head && head->key >= key)
{
node->next = head;
head = node;
length++;
return;
}
node->next = iter->next;
iter->next = node;
}
this->length++;
}
int LinkedList::search(int key){
Node* head = this->head;
while (head->key < key)
{
head = head->next;
}
if(head == nullptr){
return -1;
}
if (head->key == key)
{
return head->object;
}
else{
return -1;
}
}
void LinkedList::print(){
Node* head = this->head;
while(head){
std::cout << "( " << head->key << ", " << head->object << " ) -->";
head = head->next;
}
std::cout << std::endl;
}
void LinkedList::AddData(std::string filename, int isHeading){
using namespace std;
// working with csv in CPP
// https://www.gormanalysis.com/blog/reading-and-writing-csv-files-with-cpp/
ifstream myFile(filename);
// if(!myFile.is_open()) throw runtime_error("Could not open file");
string line, word;
int val;
if (isHeading) getline(myFile, line);
// Read data, line by line
while(getline(myFile, line))
{
// Create a stringstream of the current line
stringstream ss(line);
pair<int, int> data;
// add the column data
// of a row to a pair
getline(ss, word, ',');
data.first = stoi(word);
getline(ss, word, ',');
data.second = stoi(word);
add(data.first, data.second);
}
// Close file
myFile.close();
}