Unhandled exception at 0x006A549C in myApplication.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x01202FFC) - c++14

I am writing a program with C++ that needs to read a CSV file and store it in a binary search tree. But, when the program is reading the file, it fails in the library debugger.jmc.c and in the method void __fastcall __CheckForDebuggerJustMyCode(unsigned char *JMC_flag). Could someone help me? Thanks!
#include <algorithm>
#include <iostream>
#include <ctime>
#include <string>
#include "CSVparser.hpp"
using namespace std;
using namespace std;
struct Bid {
string bidId;
string title;
string fund;
double amount;
Bid() {
amount = 0.0;
}
};
struct Node {
Bid bid;
Node* left;
Node* right;
Node() {
left = nullptr;
right = nullptr;
}
Node(Bid aBid) : Node() {
this->bid = aBid;
}
};
class BinarySearchTree {
private:
Node* root;
void addNode(Node* node, Bid bid);
void inOrder(Node* node);
Node* removeNode(Node* node, string bidId);
public:
BinarySearchTree();
virtual ~BinarySearchTree();
void InOrder();
void Insert(Bid bid);
void Remove(string bidId);
Bid Search(string bidId);
Node* SearchNode(Node* node, string bidId);
};
BinarySearchTree::BinarySearchTree() {
root = nullptr;
}
/**
* Destructor
*/
BinarySearchTree::~BinarySearchTree() {
// recurse from root deleting every node
}
/**
* Traverse the tree in order
*/
void BinarySearchTree::InOrder() {
}
/**
* Insert a bid
*/
void BinarySearchTree::Insert(Bid bid) {
// FIXME (2a) Implement inserting a bid into the tree
if (root == nullptr) {
root = new Node(bid);
}
else {
addNode(root, bid);
}
}
/**
* Remove a bid
*/
void BinarySearchTree::Remove(string bidId) {
// FIXME (4a) Implement removing a bid from the tree
Node* nodePtr = SearchNode(root, bidId);
if (nodePtr == nullptr) {
return;
}
else {
//not yet implemented
}
}
/**
* Search for a bid
*/
Bid BinarySearchTree::Search(string bidId) {
// FIXME (3) Implement searching the tree for a bid
}
void BinarySearchTree::addNode(Node* node, Bid bid) {
// FIXME (2b) Implement inserting a bid into the tree))
//if node is larger than the bid add to the left subtree
if (stoi(node->bid.bidId) > stoi(bid.bidId)) {
if (node->left == nullptr) {
node->left = new Node(bid);
}
else {
addNode(node->left, bid);
}
}
//add to right subtree
else {
if (node->right == nullptr) {
node->right = new Node(bid);
}
else {
addNode(node->right, bid);
}
}
return;
}
void displayBid(Bid bid) {
cout << bid.bidId << ": " << bid.title << " | " << bid.amount << " | "
<< bid.fund << endl;
return;
}
/**
* Load a CSV file containing bids into a container
*
* #param csvPath the path to the CSV file to load
* #return a container holding all the bids read
*/
void loadBids(string csvPath, BinarySearchTree* bst) {
cout << "Loading CSV file " << csvPath << endl;
// initialize the CSV Parser using the given path
csv::Parser file = csv::Parser(csvPath);
try {
for (unsigned int i = 0; i < file.rowCount(); i++) {
// Create a data structure and add to the collection of bids
Bid bid;
bid.bidId = file[i][1];
bid.title = file[i][0];
bid.fund = file[i][8];
bid.amount = strToDouble(file[i][4], '$');
// push this bid to the end
bst->Insert(bid);
}
}
catch (csv::Error& e) {
std::cerr << e.what() << std::endl;
}
}
double strToDouble(string str, char ch) {
str.erase(remove(str.begin(), str.end(), ch), str.end());
return atof(str.c_str());
}
int main(int argc, char* argv[]) {
// process command line arguments
string csvPath, bidKey;
switch (argc) {
case 2:
csvPath = argv[1];
bidKey = "98105";
break;
case 3:
csvPath = argv[1];
bidKey = argv[2];
break;
default:
csvPath = "eBid_Monthly_Sales_Dec_2016.csv";
bidKey = "98105";
}
clock_t ticks;
// Define a binary search tree to hold all bids
BinarySearchTree* bst = nullptr;
Bid bid;
int choice = 0;
while (choice != 9) {
cout << "Menu:" << endl;
cout << " 1. Load Bids" << endl;
cout << " 2. Display All Bids" << endl;
cout << " 3. Find Bid" << endl;
cout << " 4. Remove Bid" << endl;
cout << " 9. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
bst = new BinarySearchTree();
ticks = clock();
loadBids("eBid_Monthly_Sales.csv", bst);
//cout << bst->Size() << " bids read" << endl;
// Calculate elapsed time and display result
ticks = clock() - ticks;
cout << "time: " << ticks << " clock ticks" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;
break;
case 2:
bst->InOrder();
break;
case 3:
ticks = clock();
bid = bst->Search(bidKey);
ticks = clock() - ticks; // current clock ticks minus starting clock ticks
if (!bid.bidId.empty()) {
displayBid(bid);
}
else {
cout << "Bid Id " << bidKey << " not found." << endl;
}
cout << "time: " << ticks << " clock ticks" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;
break;
case 4:
bst->Remove(bidKey);
break;
}
}
cout << "Good bye." << endl;
return 0;
}

Related

terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid Aborted (core dumped)

#include <iostream>
#include <vector>
using namespace std;
class House {
public:
//default constructor
House(string = "no-style", double = 0.0);
//destructor
~House();
//set the style
void setStyle(string style);
//set the cost
void setCost(double cost);
//get the style
string getStyle() const;
//get the cost
double getCost() const;
//overloaded operator: = (assignment)
House& operator = (const House &other);
//overloaded operator: == (comparison)
bool operator == (const House &other);
//overloaded operator: = (assignment)
friend ostream& operator<<(ostream& out, const House& other);
private:
string* pStyle;
double* pCost;
};
//default constructor
House::House(string style, double cost)
{
pStyle = new string{style};
pCost = new double{cost};
}
//destructor
House::~House()
{
if(pStyle != nullptr)
delete pStyle;
if(pCost != nullptr)
delete pCost;
}
//set the style
void House::setStyle(string style)
{
*pStyle = style;
}
//set the cost
void House::setCost(double cost)
{
*pCost = cost;
}
//get the style
string House::getStyle() const
{
return *pStyle;
}
//get the cost
double House::getCost() const
{
return *pCost;
}
//overloaded operator: = (assignment)
House& House::operator = (const House &other)
{
if(pStyle != nullptr)
delete pStyle;
if(pCost != nullptr)
delete pCost;
pStyle = new string{*other.pStyle};
pCost = new double{*other.pCost};
return *this;
}
//overloaded operator: == (comparison)
bool House::operator == (const House &other)
{
return (*pStyle == *other.pStyle && *pCost == *other.pCost);
}
ostream& operator<<(ostream& out, const House& other)
{
out<<"House " << other.getStyle() <<" costs:" << other.getCost()<<" dollars."<<endl;
return out;
}
void showHouses(vector<House>& houses, int houseCount) {
cout << endl << "Here are your houses: " << endl;
for(int i=0; i<houseCount; i++)
{
cout << houses.at(i);
}
}
int main() {
vector<House> houses;
House currentHouse;
int houseCount = 0; // number of houses
string style;
double cost;
int num;
cout << "Here is the currentHouse: " << currentHouse << endl;
do{
cout<<"How many houses do you want to build? (must be at least 3) ";
cin >> houseCount;
}while(houseCount<3);
cout << endl;
for(int i=0; i<houseCount; i++)
{
cout<<"What is the style for house "<<i+1<<"? ";
cin >> style;
cout<<"What is the cost for house "<<i+1<<"? ";
cin >> cost;
currentHouse.setStyle(style);
currentHouse.setCost(cost);
houses.push_back(currentHouse);
cout<<houses.at(i);
}
showHouses(houses, houseCount);
cout << endl << "Which house do you want to change? ";
cin >>num;
cout<<"What is the new style? ";
cin >> style;
cout<<"What is the new cost? ";
cin >> cost;
currentHouse = House(style, cost);
if(houses.at(num) == currentHouse)
cout<<"The new house is the same as the old house."<<endl;
else
cout<<"The houses are different."<<endl;
cout << "Copying new house to the old house ..." << endl;
houses.at(num) = currentHouse;
showHouses(houses, houseCount);
return 0;
}
The code is not working when put value of houseCount greater than 1. I have received the following error message while execute the code:
Here is the currentHouse: House no-style costs:0 dollars.
How many houses do you want to build? (must be at least 3) 3
What is the style for house 1? e
What is the cost for house 1? 2
What is the style for house 2? f
What is the cost for house 2? 5
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Aborted (core dumped)

push_back() binary tree into vector

I'm trying to put all the elements from a binary search tree into a vector, in order. Here is the function:
edit: adding instructions for clarity.
Write a class for implementing a simple binary search tree capable of storing numbers. The class should have member functions:
void insert(double x)
bool search(double x)
void inorder(vector <double> & v)
The insert function should not use recursion directly or indirectly by calling a recursive function. The search function should work by calling a private recursive member function
bool search(double x, <double> & v )
The inorder function is passed an initially empty vector v; if fills v with the inorder list of numbers stored in the binary search tree. Demonstrate the operation of the class using a suitable driver program.
EDIT: Added full code for clarity.
#include "stdafx.h"
#include <iostream>
#include <vector>
class BinaryTree {
private:
struct TreeNode {
double value;
TreeNode *left;
TreeNode *right;
TreeNode(double value1,
TreeNode *left1 = nullptr,
TreeNode *right1 = nullptr) {
value = value1;
left = left1;
right = right1;
}
};
TreeNode *root; //pointer to the root of the tree
bool search(double x, TreeNode *t) {
while (t) {
std::cout << "running through t." << std::endl;
if (t->value == x) {
return true;
}
else if (x < t->value) {
std::cout << "wasn't found, moving left." << std::endl;
search(x, t->left);
}
else {
std::cout << "wasn't found, moving right." << std::endl;
search(x, t->right);
}
}
std::cout << "wasn't found." << std::endl;
return false;
}
public:
std::vector<TreeNode> v;
BinaryTree() {
root = nullptr;
}
void insert(double x) {
TreeNode *tree = root;
if (!tree) {
std::cout << "Creating tree." << x << std::endl;
root = new TreeNode(x);
return;
}
while (tree) {
std::cout << "Adding next value." << std::endl;
if (tree->value == x) return;
if (x < tree->value) {
tree = tree->left;
tree->value = x;
}
else {
tree = tree->right;
tree->value = x;
}
}
}
bool search(double x) {
return search(x, root);
}
void inOrder(std::vector <double> & v) {
{
if (left)
left->inOrder(v);
v.push_back(value);
if (right)
right->inOrder(v);
}
}
TreeNode* left = nullptr;
TreeNode* right = nullptr;
double value;
};
int main() {
BinaryTree t;
std::cout << "Inserting the numbers 5, 8, 3, 12, and 9." << std::endl;
t.insert(5);
t.insert(8);
t.insert(3);
t.insert(12);
t.insert(9);
std::cout << "Looking for 12 in tree." << std::endl;
if (t.search(12)) {
std::cout << "12 was found." << std::endl;
}
std::cout << "Here are the numbers in order." << std::endl;
return 0;
}
I'm unable to get the values to push into the vector. Any ideas as to how I can accomplish this?
You would normally do this recursively:
#include <vector>
class TreeNode {
void inOrder(std::vector<double>& v) const
{
if (left)
left->inOrder(v);
v.push_back(value);
if (right)
right->inOrder(v);
}
TreeNode* left = nullptr;
TreeNode* right = nullptr;
double value;
};
Edit: added #include <vector>
Edit2: That is how I would do it. Feel free to ask any questions:
#include <iostream>
#include <vector>
class BinaryTree {
private:
struct TreeNode {
double value;
TreeNode *left = nullptr;
TreeNode *right = nullptr;
TreeNode(double value1)
: value(value1)
{}
void inOrder(std::vector <double> & v) {
if (left)
left->inOrder(v);
v.push_back(value);
if (right)
right->inOrder(v);
}
};
TreeNode *root = nullptr; //pointer to the root of the tree
bool search(double x, TreeNode *t) {
while (t) {
std::cout << "running through t." << std::endl;
if (t->value == x) {
return true;
}
else if (x < t->value) {
std::cout << "wasn't found, moving left." << std::endl;
return search(x, t->left);
}
else {
std::cout << "wasn't found, moving right." << std::endl;
return search(x, t->right);
}
}
std::cout << "wasn't found." << std::endl;
return false;
}
public:
BinaryTree() {}
void insert(double x) {
TreeNode *tree = root;
if (!tree) {
std::cout << "Creating tree." << x << std::endl;
root = new TreeNode(x);
return;
}
while (tree) {
std::cout << "Adding next value." << std::endl;
if (tree->value == x) return;
if (x < tree->value) {
if (!tree->left)
{
tree->left = new TreeNode(x);
return;
}
tree = tree->left;
}
else {
if (!tree->right)
{
tree->right = new TreeNode(x);
return;
}
tree = tree->right;
}
}
}
bool search(double x) {
return search(x, root);
}
void inOrder(std::vector<double>& v)
{
root->inOrder(v);
}
};
int main() {
BinaryTree t;
std::cout << "Inserting the numbers 5, 8, 3, 12, and 9." << std::endl;
t.insert(5);
t.insert(8);
t.insert(3);
t.insert(12);
t.insert(9);
std::cout << "Looking for 12 in tree." << std::endl;
if (t.search(12)) {
std::cout << "12 was found." << std::endl;
}
std::cout << "Here are the numbers in order." << std::endl;
std::vector<double> v;
t.inOrder(v);
std::cout << "values in order:";
for (double val : v)
{
std::cout << " " << val;
}
std::cout << std::endl;
return 0;
}

Not able to store data in a private member variable from a const member function - FIX8 c++

This is my header :
class my_router_client : public FIX8::my::mine_Router {
private:
mine_session_client& _session;
mutable std::vector<std::string> vSymbolList;
public:
my_router_client(mine_session_client& session) : _session(session) {}
virtual bool operator() (const FIX8::my::SecurityList *msg) const;
void sendToServer(FIX8::Message *);
void logout();
void itertool() const;
};
I am trying to save the data obtained from security list response to the vSymbolList vector. After handling security response I am trying to iterate through the vector by itertool method. But every time I end up with an empty vector. I tried printing the contents of the vector inside securitylist response function
virtual bool operator() (const FIX8::CX::SecurityList *msg) const;
and I am able to print the contents. Is it some kind of race condition inside threads?
this is the security list response handler
bool cx_router_client::operator() (const CX::SecurityList *msg) const
{
GroupBase *dad(msg->find_group< CX::SecurityList::NoRelatedSym >());
if (dad) {
for (size_t cnt(0); cnt < dad->size(); ++cnt) {
CX::Symbol symbol;
MessageBase *details(dad->get_element(cnt));
details->get(symbol);
string ss;
ss = symbol();
vSymbolList.push_back(ss);
// cout << "at :: :: " << vSymbolList[cnt] << endl;
}
cout << "no of symbol : " << vSymbolList.size() << endl;
hypersleep<h_seconds>(1);
}
return true;
}
This is the itertool method :
void my_router_client::itertool() const
{
cout << "symbol list vector size inside itertool:: " << vSymbolList.size() << endl;
stringstream ss;
ss << this_thread::get_id();
uint64_t id = stoull(ss.str());
cout << "Thread ID #### " << id << endl;
vector<string>::iterator it = this->vSymbolList.begin();
while (it != vSymbolList.end()) {
cout << *it << endl;
it++;
}
}
This is how I use the them in main :
int main()
{
const string conf_file("myfix_client.xml");
unique_ptr<ClientSessionBase> mc(new ClientSession<mine_session_client>(my::ctx(), conf_file, "DLD1"));
mc->start(false, next_send, next_receive, mc->session_ptr()->get_login_parameters()._davi());
hypersleep<h_seconds>(1);
my_router_client *test = new my_router_client(static_cast< mine_session_client& > (*mc->session_ptr()));
hypersleep<h_seconds>(1);
test->sendToServer(makeSecurityListRequest());
hypersleep<h_seconds>(1);
test->itertool();
while(1);
}

.compare not matching a string pulled from an object

I am trying to go threw a vector of Student objects. If I find a matching ID to the one I am searching for it will display their info.
However, when I try to find a specific ID .compare isn't seeing a match even though it should.
My output: first line is the ID I am looking for, second is the current ID being looked at, then is the result of the compare.
a11111111
a22222222
-1
no match
a11111111
a11111111
-1
no match
Asked for more of the code so here is the entire program: (issue in displayID)
header file
#ifndef structures_h
#define structures_h
#include <vector>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <map>
using namespace std;
main program
#endif
typedef pair<string, string> Name; // first name, last name
typedef map<string, int> Grades; // map courses to scores
#include "struct.h"
class Student {
public:
void display(ostream& os) const;
void setId(string);
void setName(string, string);
void setGrades(string, int);
string getId();
string getName();
void getGrades();
bool operator<(const Student &rhs) const { return id_ < rhs.id_; }
private:
string id_; // e.g. "a22222222"
Name name_; // e.g. {"ned", "flanders"}
Grades grades_;
};
void Student::setId(string id) {
id_ = id;
}
string Student::getId() {
return id_;
}
void Student::setName(string first, string last) {
name_ = pair<string,string>(first, last);
}
string Student::getName() {
return get<0>(name_) + ' ' + get<1>(name_);
}
void Student::setGrades(string course, int score) {
grades_.insert(make_pair(course, score));
}
void Student::getGrades() {
for(auto it = grades_.begin(); it != grades_.end(); ++it) {
cout << it -> first << ' ' << it -> second << endl;
}
}
vector<Student> addStudent(int count, int x, vector<Student>& vStu, string file) {
string line, first, last;
ifstream infile(file);
while (getline(infile, line)) {
vStu.push_back(Student());
vStu[count].setId(line);
getline(infile, line);
istringstream iss(line);
if (!(iss >> first >> last)) {
cout << "failed to get name" << endl;
break;
}
vStu[count].setName(first, last);
getline(infile, line);
istringstream iss2(line);
if (!(iss2 >> x)) {
cout << "failed to get class number" << endl;
break;
}
for (int i = 0; i < x; i++) {
string sClass;
int grade;
getline(infile, line);
istringstream iss3(line);
if (!(iss3 >> sClass >> grade)) {
cout << "failed to get class and grade" << endl;
break;
}
vStu[count].setGrades(sClass, grade);
}
count++;
}
return vStu;
}
void display(vector<Student>& vStu) {
sort(vStu.begin(), vStu.end());
cout << endl;
int count = vStu.size();
for (int i = 0; i<count;i++) {
cout << vStu[i].getId() << endl;
cout << vStu[i].getName() << endl;
vStu[i].getGrades();
cout << endl;
}
}
void displayID(vector<Student>& vStu, string ID) {
int count = vStu.size();
string test;
ID = "a11111111";
for (int i = 0; i<count;i++) {
cout<< endl;
test = vStu[i].getId();
cout << ID << endl;
cout << test << endl;
cout << ID.compare(test) << endl;
if (ID.compare(test) == 0) {
cout << "match" << endl;
cout << vStu[i].getId() << endl;
cout << vStu[i].getName() << endl;
vStu[i].getGrades();
cout << endl;
} else {
cout << "no match" << endl;
}
}
cout << endl;
}
void mainMenu(vector<Student>& vStu) {
string input;
string word;
vector<string> com;
while(1) {
cout << "Enter command: ";
getline(cin,input);
istringstream iss(input);
while(iss >> word) {
com.push_back(word);
}
for (int i = 0; i < (int)com.size(); i++) {
transform(com[i].begin(), com[i].end(), com[i].begin(), ::tolower);
if (com[i] == "show") {
display(vStu);
} else if (com[i] == "showid") {
displayID(vStu, "a11111111");
}
}
com.clear();
}
}
int main(int argc, char *argv[]) {
vector<Student> vStu;
int count = 0, x = 0;
if (argc != 2) {
cout << "Incorrectly called" << endl;
cout << " " << argv[0] << ' ' << "<filename>" << endl;
return 1;
}
addStudent(count, x, vStu, argv[1]);
mainMenu(vStu);
}
The only possibility I see is that there is some whitespace at the end of the string that gets passed into your function. Try trimming the end of the string's like this this thread suggests before comparing and see if they still don't compare correctly.

Doubly Linked List: Sorting nodes in ascending order

I'm working on a program using doubly linked lists. I have already gotten the functionality to insert nodes, remove nodes, retrieve the value from a node, display the list, output the size of the list, telling if the list is empty, and deleting all nodes.
What I am having problems with is sorting the values in ascending order, and finding which node a certain value is in.
I am going to a help lab tomorrow I just thought I would see if anyone could help before then.
I have no idea what to do about sort().
I have find() somewhat working, but when I ask it to find the node of a value, it just returns the value I entered.
EDIT: deleteAll() now works properly!
#include <iostream>
#include <limits>
using namespace std;
struct node
{
int data; //data
struct node *next; //link to next node
struct node *back; //link to previous node
};
class LinkedList //class LinkedList
{
struct node *root;
struct node *end;
int size;
public:
LinkedList() : root(NULL), size(0){}
bool isEmpty() const { return (root == NULL); }
void create(); //cleate list
void insert(); //insertion
void remove(); //deletion
void display(); //display list
void sort(); //sort list
void find(); //find a values' node
void deleteAll(); //delete all values
void retreive(); //retrive node
void getSize(); //return the number of nodes
};
//Creating a new list
void LinkedList::create()
{
struct node *nxt_node;
struct node *prev_node;
int value;
int n;
int i;
root = nxt_node = NULL;
cout << "How many nodes will the list have?: ";
cin >> n;
cout << "Enter the numbers to create the list: ";
for(i = 1; i <= n; i++)
{
cin >> value;
nxt_node = new node;
nxt_node->data = value;
nxt_node->next = NULL;
nxt_node->back = NULL;
if(root == NULL)
{
root = nxt_node;
}
else
{
prev_node->next = nxt_node;
nxt_node->back = prev_node;
}
prev_node = nxt_node;
}
end = nxt_node;
size = n;
cout << endl;
cout << "The list has been created!" << endl;
cout << endl;
display();
}
//Displaying the list
void LinkedList::display()
{
if(isEmpty())
{
cout << "The list is empty!" << endl;
return;
}
else
{
struct node *tmp = root;
cout << "The list is: ";
cout << "root -> ";
while(tmp != NULL)
{
cout << tmp->data << " -> ";
tmp = tmp->next;
}
cout << "end";
cout << endl << endl;
}
}
//Instert a node anywhere
void LinkedList::insert()
{
int pos;
int dat;
struct node *ptr_b;
struct node *ptr_f;
struct node *tmp;
cout << "At what node do you want to insert the new data?: " << endl;
cout << "(If the node is not found the data will be added to the beginning)" << endl;
cout << "Node: ";
cin >> pos;
cout << endl;
cout << "Enter the data to be inserted: ";
cin >> dat;
ptr_b = root;
tmp = new node;
tmp->data = dat;
while(ptr_b->next != NULL && ptr_b->data != pos)
{
ptr_b = ptr_b->next;
}
if(ptr_b->next == NULL && ptr_b->data != pos) //insertion to front
{
root->back = tmp;
tmp->next = root;
tmp->back = NULL;
root = tmp;
}
else if(ptr_b->next == NULL && ptr_b->data == pos) //insertion at the end
{
ptr_b->next = tmp;
tmp->next = NULL;
tmp->back = ptr_b;
end = tmp;
}
else // insertion between two nodes
{
ptr_f = ptr_b->next;
tmp->next = ptr_b->next;
tmp->back = ptr_b;
ptr_b->next = tmp;
ptr_f->back = tmp;
}
size++;
cout << "The new data has been inserted!" << endl << endl;
display();
}
//remove any node
void LinkedList::remove()
{
int loc;
int dat;
struct node *ptr_b;
struct node *ptr_f;
struct node *tmp;
cout << "Enter the node to delete: ";
cin >> loc;
tmp = root;
if(loc < size && loc > 0) //return the value at loc
{
int ind = 0;
while(++ind < loc && tmp->next != NULL)
{
tmp = tmp->next;
}
}
if(tmp->next == NULL && tmp->data != loc) //Data not found
{
cout << "Node not found!" << endl << endl;
return;
}
else if(tmp->next == NULL && tmp->data == loc) //Delete from the end of the list
{
ptr_b = tmp->back;
dat = tmp->data;
ptr_b->next = NULL;
end = ptr_b;
}
else //Delete between two nodes or first node
{
dat = tmp->data;
if(root == tmp) //delete the first node
{
root = tmp->next;
ptr_f = root;
ptr_f->back = NULL;
}
else //deletion between two nodes
{
dat = tmp->data;
ptr_b = tmp->back;
ptr_b->next = tmp->next;
ptr_f = ptr_b->next;
ptr_f->back = ptr_b;
}
}
delete tmp;
size--;
cout << endl;
cout << "The node has been deleted!" << endl << endl;
display();
}
//retrieve a nodes data value
void LinkedList::retreive()
{
int loc;
//if the list is empty, say so
if(isEmpty())
{
cout << "The List is empty!";
return;
}
else
{
//If the list is not empty
cout << "What nodes' value do you want to retrieve?: ";
cin >> loc;
if(loc < size && loc > 0) //return the value at loc
{
struct node *tmp = root;
int ind = 0;
while(++ind < loc && tmp->next != NULL)
{
tmp = tmp->next;
}
cout << "The nodes value is: " << tmp->data << endl;
cout << endl;
}
else //if the node is out of range
{
cout << "Invailid location!" << endl;
}
}
}
//sort the list in acending order
void LinkedList::sort()
{
cout << "The list has been sorted!" << endl;
}
//delete all the values
void LinkedList::deleteAll()
{
struct node *tmp;
for(int i = 1; i < size; i++)
{
while(root != NULL)
{
tmp = root;
root = tmp->next;
delete tmp;
}
}
display();
}
//find a values' node
void LinkedList::find()
{
int value;
//if the list is empty, say so
if(isEmpty())
{
cout << "The List is empty!";
return;
}
else
{
//If the list is not empty
cout << "What values' node do you want to find?: ";
cin >> value;
struct node *tmp = root;
int ind = 0;
while(++ind < value && tmp->data != value)
{
tmp = tmp->next;
}
if(tmp->next == NULL && tmp->data != value) //Data not found
{
cout << "Value not found!" << endl << endl;
return;
}
else
{
cout << "The value is at node: " << tmp->data << endl;
cout << endl;
}
}
}
void LinkedList::getSize()
{
cout << "The list has " << size << " nodes" << endl << endl;
}
int main()
{
LinkedList list;
list.create(); //create a new list
int choice;
while(1)
{
cout << "What would you like to do? (1-7): " << endl;
cout << "1. Insert a number" << endl;
cout << "2. Delete a node" << endl;
cout << "3. Delete ALL values" << endl;
cout << "4. Retrieve a nodes' value" << endl;
cout << "5. Retrives a values' node" << endl;
cout << "6. Return the size of the list" << endl;
cout << "7. Exit the program" << endl;
cout << endl;
cout << "Enter your choice (1-7): ";
cin >> choice;
cout << endl;
switch(choice)
{
case 1: //insertion
list.insert();
break;
case 2: //deletion
list.remove();
break;
case 3: //delete all the values
list.deleteAll();
break;
case 4: //retrieve a nodes' value
list.retreive();
break;
case 5: //retrieve a values' node
list.find();
break;
case 6: //returns the lists size
list.getSize();
break;
case 7: //Exit the program
exit(0);
break;
default:
cout << "Please enter a vaild choice (1-7)!" << endl;
break;
}
}
return 0;
}
Any help would be appreciated. I understand if you don't want to help on both things, just getting the one I have close to being done (find()) would be awesome!
Thanks.
For deleteAll your for loop needs to start from 0, not from 1 (or go to size+1). Think about a list of size 1, your code would not execute, which is why there is 1 node left in your linked list. Your code also needs to be rethought. Rather than a for loop maybe a while loop?
struct node *tmp;
while (root != NULL)
{
tmp = root;
root = root->next;
root->back = NULL; //Is this even necessary? You're deleting ALL nodes.
delete tmp;
}
display();
As for your find function, you've set it to return void (nothing). It's printing the node value because you tell it to but you're not returning the node. You need to think about what find should return (the node, or null).
I would suggest looking up QuickSort to sort your list. Because this is a specialized case you'll have to tailor the QuickSort to sort by node->value and when you sort you'll have to make sure your nodes point to the correct previous and next nodes when you swap values. Continue posting your code as you run into more errors and please make sure you let us know what you've tried and what's not working, we'd be happy to help point you in the right direction.

Resources