push_back() binary tree into vector - c++11

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;
}

Related

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

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;
}

Why move assignment is called

Please tell me why move assignment is called in the following code.
In expression return Foo(static_cast<int>(value));, static_cast<int>(value) is rvalue, so move assignment is called. However, in expression return Foo(value);, value is an lvalue. Why move assignment is called instead of Foo(int val);
#include <bits/stdc++.h>
using namespace std;
class Foo {
public:
Foo() {}
Foo(int val)
{
value = val;
}
Foo(Foo& foo)
{
value = foo.value;
cout << "call Foo(Foo& foo)" << endl;
}
Foo(Foo&& foo)
{
value = foo.value;
foo.value = 0;
cout << "call Foo(Foo &&foo)" << endl;
}
Foo& operator=(Foo &foo)
{
value = foo.value;
cout << "call operator=(Foo& foo)" << endl;
return *this;
}
Foo& operator=(Foo &&foo)
{
value = foo.value;
foo.value = 0;
cout << "call operator=(Foo&& foo)" << endl;
return *this;
}
private:
int value;
};
Foo operator"" fo(unsigned long long value)
{
if (value < INT_MAX) {
// return Foo(static_cast<int>(value)); // call operator=(Foo&& foo)
return Foo(value); // call operator=(Foo&& foo)
} else {
throw "Over Range";
}
}
int main()
{
Foo foo;
foo = 123fo;
return 0;
}

How to keep all properties of graph read by boost::read_graphviz?

Suppose you want to read in a .dot graph into boost where there could be properties you do not recognize. It is easy to ignore them (by passing ignore_other_properties to the dynamic_properties constructor) but what if you wanted all the properties added to dynamic_properties instead?
The below code demonstrates the problem. The handle_custom_properties is a copy of ignore_other_properties and the code will compile / run, reporting "3 vertices, 2 edges." What needs to be added to handle_custom_properties so that, on return, dp will contain a property "label" and node A will have value "x" for the label property?
#include <iostream>
#include <string>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/exception/exception.hpp>
#include <boost/exception/diagnostic_information.hpp>
struct vertex_p {
std::string node_id;
};
typedef boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS, vertex_p> graph_t;
boost::shared_ptr<boost::dynamic_property_map>
handle_custom_properties(const std::string& s,
const boost::any& k,
const boost::any& v) {
// What goes in here to add dynamic property map for property "s" which key-value pair <k,v>?
// What ignore_other_properties does
return boost::shared_ptr<boost::dynamic_property_map>();
}
int main() {
std::string str(R"(graph {
A [ label="x" ]
B
C
A -- B
A -- C
}
)");
try {
graph_t g;
boost::dynamic_properties dp{handle_custom_properties};
dp.property("node_id", get(&vertex_p::node_id, g));
if (boost::read_graphviz(str, g, dp)) {
std::cout << "read_graphviz returned success" << std::endl;
std::cout << "graph stats:" << std::endl;
std::cout << " " << g.m_vertices.size() << " vertices" << std::endl;
std::cout << " " << g.m_edges.size() << " edges" << std::endl;
}
else {
std::cout << "read_graphviz returned failure" << std::endl;
}
}
catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
catch (boost::exception& e) {
std::cerr << boost::diagnostic_information(e) << std::endl;
}
}
I was not able to find an existing class to solve this but implementing a dynamic_property_map in terms of a std::map worked:
template<typename TKey, typename TValue>
class dynamic_property_map_impl : public boost::dynamic_property_map {
std::map<TKey, TValue> map_;
public:
boost::any get(const boost::any& key) override { return map_[boost::any_cast<TKey>(key)]; }
std::string get_string(const boost::any& key) override { std::ostringstream s; s << map_[boost::any_cast<TKey>(key)]; return s.str(); }
void put(const boost::any& key, const boost::any& value) override { map_[boost::any_cast<TKey>(key)] = boost::any_cast<TValue>(value); }
const std::type_info& key() const override { return typeid(TKey); }
const std::type_info& value() const override { return typeid(TValue); }
};
boost::shared_ptr<boost::dynamic_property_map>
handle_custom_properties(const std::string&,
const boost::any&,
const boost::any&) {
return boost::make_shared<dynamic_property_map_impl<unsigned, std::string>>();
}
Changing the graph and printing out the properties shows all the property maps were added:
std::string str(R"(graph {
A [ label="x", stuff="y" ]
B
C [ happy="yes" ]
A -- B
A -- C
}
)");
...
std::cout << "properties:" << std::endl;
for (const auto& p : dp) {
std::cout << " " << p.first << std::endl;
}
Outputs
read_graphviz returned success
graph stats:
3 vertices
2 edges
properties:
happy
label
node_id
stuff

.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