Converting Infix to Postfix Using Stack - c++11

I'm having trouble creating a program that will convert infix to postfix. My code is as follows:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define DEFAULT_SIZE 20
/*
*
*/
class Stack {
char *arr;
int tos, capacity;
public:
//Constructors
Stack();
Stack(int size);
//Destructor
~Stack();
//Methods
void push(char a);
char pop();
int get_size();
bool is_empty();
bool is_full();
void display();
char get_top();
};
Stack::Stack() {
arr = new char[DEFAULT_SIZE];
tos = 0;
capacity = DEFAULT_SIZE;
}
Stack::Stack(int size) {
arr = new char[size];
tos = 0;
capacity = size;
}
Stack::~Stack() {
delete[] arr;
}
void Stack::push(char a) {
if (!is_full())
arr[tos++] = a;
else
cout << "Sorry, the stack is full. Push failed!" << endl;
}
char Stack::pop() {
if (!is_empty())
return arr[--tos];
else {
cout << "Sorry, the stack is empty. Pop failed!" << endl;
return -1;
}
}
char Stack::get_top() {
if (!is_empty())
return arr[tos - 1];
else {
cout << "Sorry, the stack is empty. Pop failed!" << endl;
return 'E';
}
}
int Stack::get_size() {
return tos;
}
bool Stack::is_empty() {
if (tos == 0)
return true;
else
return false;
}
bool Stack::is_full() {
if (tos == capacity)
return true;
else
return false;
}
void Stack::display() {
if (tos == 0)
cout << "The stack is empty" << endl;
else {
for (int i = 0; i<tos;i++)
cout << arr[i] << " ";
cout << endl;
}
}
int main() {
Stack stack(50);
string infix = "(1+3)*2/(6-4)^2";
stringstream ss;
for (char c : infix) {
if ('0' <= c && c <= '9') {
ss << c;
}
else if (c == '(') {
continue;
}
else if (c == ')') {
ss << stack.pop();
stack.pop();
}
else if (c == '^' || c == '*' || c == '/' || c == '+' || c == '-') {
stack.push(c);
}
}
string postfix = ss.str();
cout << postfix;
I know what my issue is, I just dont understand or comprehend how to solve it. This code currently outputs 13+264-2. It needs to output 13+2*64-2^/. I know my issues is with my last else if statement in int main(). I dont understand how to rearrange the operators behind the operands.
Anything in parentheses is passed into the stream correctly, because I can wait until the closing parenthesis is hit to add in the operator. I can't visualize how to make that work for things not in parentheses though. Can anyone offer any advice?

Related

MPI gather doesn't work with customized datatype

I tried two ways for the same issue, one works and the other doesn't. The following version works, returning a value of 4.
int gather_list()
{
mpi::environment env;
mpi::communicator world;
std::srand(time(0) + world.rank());
int my_number = std::rand();
std::vector<int> tmp_vec;
tmp_vec.push_back(my_number);
tmp_vec.push_back(my_number + 1);
if (world.rank() == 0)
{
std::vector<int> all_numbers;
gather(world, &tmp_vec[0], tmp_vec.size(), all_numbers, 0);
std::cout << all_numbers.size() << std::endl;
} else
{
gather(world, &tmp_vec[0], tmp_vec.size(), 0);
}
return 0;
}
The following version doesn't work, returning a value of 2.
class ArchivableVecInt : public std::vector<int>
{
public:
ArchivableVecInt() = default;
explicit ArchivableVecInt(const std::vector<int> &vec)
{
auto base_ptr = static_cast<std::vector<int> *>(this);
*base_ptr = vec;
}
template<class Archiver>
void serialize(Archiver &ar, unsigned int)
{
for (auto i: *this)
{
ar & i;
}
}
protected:
};
int gather_list()
{
mpi::environment env;
mpi::communicator world;
std::srand(time(0) + world.rank());
int my_number = std::rand();
std::vector<int> tmp_vec;
tmp_vec.push_back(my_number);
tmp_vec.push_back(my_number + 1);
ArchivableVecInt my_vec(tmp_vec);
if (world.rank() == 0)
{
std::vector<ArchivableVecInt> all_numbers;
gather(world, my_vec, all_numbers, 0);
for (int proc = 0; proc < world.size(); ++proc)
std::cout << "Process #" << proc << " thought of "
<< all_numbers[proc].size() << std::endl;
} else
{
gather(world, my_vec, 0);
}
return 0;
}
I tried 2 processes, while rank 0 returns a value of 2, rank 1 returns zero. Seems the gather(world, my_vec, 0) didn't work, why?
result as below.
Thanks in advance.
In your second example your receive buffer is a vector<vector<int>> meaning that the data is not contiguous. MPI needs contiguous buffers.

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)

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

.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