I am trying to create a doubly linked list:
class DblLinkedBag
{
private:
struct node{
string data;
node* next;
node* prev;
}*start=NULL;
int itemCount;
string item;
node *head;
node *tail;
public:
DblLinkedBag();
~DblLinkedBag();
int getCurrentSize();
bool isEmpty();
string add(string value);
bool remove(string item);
void clear();
bool contains(string target);
int getFrequencyOf();
string toVector();
string getItem();
void display();
};
So far, I have gotten add, isEmpty, getCurrentSize and clear to work. Now I just need the rest to work and I am having a hard time. My professor gave us a requirement that the class had to be implemented like this:
#include <iostream>
#include <string>
#include "LinkedBag.h"
using namespace std;
void displayBag(LinkedBag<string>& bag)
{
cout << "The bag contains " << bag.getCurrentSize()
<< " items:" << endl;
vector<string> bagItems = bag.toVector();
int numberOfEntries = (int) bagItems.size();
for (int i = 0; i < numberOfEntries; i++)
{
cout << bagItems[i] << " ";
} // end for
cout << endl << endl;
} // end displayBag
void copyConstructorTester()
{
LinkedBag<string> bag;
string items[] = {"zero", "one", "two", "three", "four", "five"};
for (int i = 0; i < 6; i++)
{
cout << "Adding " << items[i] << endl;
bool success = bag.add(items[i]);
if (!success)
cout << "Failed to add " << items[i] << " to the bag." << endl;
}
displayBag(bag);
LinkedBag<string> copyOfBag(bag);
cout << "Copy of bag: ";
displayBag(copyOfBag);
cout << "The copied bag: ";
displayBag(bag);
} // end copyConstructorTester
void bagTester()
{
LinkedBag<string> bag;
cout << "Testing the Link-Based Bag:" << endl;
cout << "isEmpty: returns " << bag.isEmpty()
<< "; should be 1 (true)" << endl;
displayBag(bag);
string items[] = {"one", "two", "three", "four", "five", "one"};
cout << "Add 6 items to the bag: " << endl;
for (int i = 0; i < 6; i++)
{
bag.add(items[i]);
} // end for
displayBag(bag);
cout << "isEmpty: returns " << bag.isEmpty()
<< "; should be 0 (false)" << endl;
cout << "getCurrentSize: returns " << bag.getCurrentSize()
<< "; should be 6" << endl;
cout << "Try to add another entry: add(\"extra\") returns "
<< bag.add("extra") << endl;
cout << "contains(\"three\"): returns " << bag.contains("three")
<< "; should be 1 (true)" << endl;
cout << "contains(\"ten\"): returns " << bag.contains("ten")
<< "; should be 0 (false)" << endl;
cout << "getFrequencyOf(\"one\"): returns "
<< bag.getFrequencyOf("one") << " should be 2" << endl;
cout << "remove(\"one\"): returns " << bag.remove("one")
<< "; should be 1 (true)" << endl;
cout << "getFrequencyOf(\"one\"): returns "
<< bag.getFrequencyOf("one") << " should be 1" << endl;
cout << "remove(\"one\"): returns " << bag.remove("one")
<< "; should be 1 (true)" << endl;
cout << "remove(\"one\"): returns " << bag.remove("one")
<< "; should be 0 (false)" << endl;
cout << endl;
displayBag(bag);
cout << "After clearing the bag, ";
bag.clear();
cout << "isEmpty: returns " << bag.isEmpty()
<< "; should be 1 (true)" << endl;
} // end bagTester
int main()
{
copyConstructorTester();
bagTester();
return 0;
} // end main
So far this is what I have.
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class DblLinkedBag
{
private:
struct node{
string data;
node* next;
node* prev;
}*start=NULL;
int itemCount;
string item;
node *head;
node *tail;
public:
DblLinkedBag();
~DblLinkedBag();
int getCurrentSize();
bool isEmpty();
string add(string value);
bool remove(string item);
void clear();
bool contains(string target);
int getFrequencyOf();
string toVector();
string getItem();
void display();
};
DblLinkedBag::DblLinkedBag()
{
itemCount=0;
item;
}
string DblLinkedBag::add(string value)
{
node* n;
cout<<itemCount<<endl;
if(itemCount==0)
{
n=new node;
n->data=value;
n->prev=NULL;
head=n;
tail=n;
}
if(itemCount>0 && itemCount<7)
{
n= new node;
n->data=value;
n->prev=tail;
tail->next=n;
tail=n;
}
itemCount++;
return value;
}
void DblLinkedBag::display()
{
struct node* temp=start;
while(temp != NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
int DblLinkedBag::getCurrentSize()
{
return itemCount;
}
bool DblLinkedBag::contains(string target)
{
//need help here, supposed to tell if the linked list contains a certain //string
bool found= false;
node* curPtr=start;
int i=0;
while (!found && (curPtr!=NULL)&& (i<itemCount))
{
if(target==curPtr->data)
{
found=true;
}
else
{
i++;
curPtr=curPtr->next;
}
}
return found;
}
bool DblLinkedBag::isEmpty()
{
bool empty;
if (itemCount==0)
{
empty=true;
}
else
empty=false;
return empty;
}
void DblLinkedBag::clear()
{
node* nodeToDelete=start;
while (start != NULL)
{
start=start->next;
nodeToDelete->next=NULL;
delete nodeToDelete;
}
itemCount=0;
}
bool DblLinkedBag::remove(string item)
{
//need help here
}
string DblLinkedBag::toVector()
{
//need help here this is supposed to send the linked list to a vector
vector<string> vct;
node* curPtr= start;
int counter = 0;
while ((curPtr != NULL) && (counter < itemCount))
{
vct.push_back(curPtr->data);
curPtr = curPtr->next;
counter++;
}
}
int DblLinkedBag::getFrequency()
{//supposed to show how many of a certain item are in the linked list
DblLinkedBag::~DblLinkedBag()
{
}
Any help implementing these class functions to create the other functions my professor gave me would be appreciated, I have tried all different kinds of implementations and I cannot seem to figure it out.
First: your method DblLinkedBag::clear has a error, nodeToDelete never change (just deletes first node)
bool DblLinkedBag::remove(string item)
{
node* curPtr=start;
while (curPtr!=NULL)
{
if(item==curPtr->data)
{
if(curPtr->prev) curPtr->prev->next = curPtr->next;
if(curPtr->next) curPtr->next->prev = curPtr->prev;
delete curPtr;
itemCount--;
return true;
}
else
{
curPtr=curPtr->next;
}
}
return false;
}
What do you expect getFrequency() to do?
Related
I am working on an assignment for school. I have to create an AVLTree, read data from a text file and then create Professor object with that data. However, when I try and search for a Professor by name, it can't be found. It keeps defaulting to Michael Scott in the program and can't find who I'm looking for. My readFromFile function works perfectly and gets me all the data from the file, so I have the data. At this point it's a matter of issues with the AVL Tree. I'll link everything below.
Driver.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "AVLTree.h"
using namespace std;
void readFromFile(AVLTree *treeAccess) {
int numOfProfs = 0;
string line;
const char *path="/Users/collinchappell/Desktop/Program4Official/Program4Official/ProfessorData.txt";
fstream myFile (path, ios::in);
if (!myFile) {
cout << "Sorry can't read ProfessorData.txt!" << endl;
}
else {
// Splitting up all the data in the .txt file and the looping through using string stream
// Not the best solution, however nothing else would work for me so this is what I went with.
while (getline(myFile, line)) {
string n;
string nT;
string s;
int b1,b2,b3,b4,b5,b6,b7;
replace(line.begin(), line.end(), '$', ' ');
stringstream ss(line);
for (int k = 0; k < 11; k++) {
ss >> n;
ss >> nT;
n = n + " " + nT;
ss >> s;
ss >> b1;
ss >> b2;
ss >> b3;
ss >> b4;
ss >> b5;
ss >> b6;
ss >> b7;
numOfProfs++;
Professor p(n, s, b1, b2, b3, b4, b5, b6, b7);
cout << p;
treeAccess->insertNode(n, &p);
}
}
}
cout << numOfProfs << " Proffesors have added from the file." << endl << endl;
}
int main() {
AVLTree tree;
readFromFile(&tree);
bool cont = true;
while (cont) {
cout << "Which Computer Science professor do you want details about?" << endl;
tree.displayInOrder();
cout << endl << endl << "Type Professor Name: ";
string typeName;
getline(cin, typeName);
while (tree.searchNode(typeName) == NULL) {
cout << "Couldn't find that professor! Please type another: ";
getline(cin, typeName);
}
cout << tree.searchNode(typeName);
cout << "Would you like to search another? (Y/N): ";
string ans;
cin >> ans;
if (ans == "y" || ans == "Y") {
continue;
}
else if (ans == "n" || ans == "N") {
return 0;
}
}
return 0;
}
AVLTree.h:
#ifndef AVLTree_h
#define AVLTree_h
#include <iostream>
#include "Professor.h"
using namespace std;
class AVLTree {
private:
// TreeNode structure
struct TreeNode {
string name;
Professor *prof;
struct TreeNode* left;
struct TreeNode* right;
};
// Root of tree
TreeNode* root;
// Function declarations
void insert(TreeNode *&nodePtr, TreeNode *&newNode);
void destroySubTree(TreeNode *nodePtr);
void displayInOrder(TreeNode *nodePtr) const;
int height(TreeNode *nodePtr);
int diff(TreeNode *nodePtr);
void balance(TreeNode *&temp);
TreeNode* l_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->right;
parent->right = temp->left;
temp->left = parent;
return temp;
}
TreeNode* r_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->left;
parent->left = temp->right;
temp->right = parent;
return temp;
}
TreeNode* lr_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->left;
parent->left = (l_rotation(temp));
return r_rotation(parent);
}
TreeNode* rl_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->right;
parent->right = (r_rotation(temp));
return l_rotation(parent);
}
public:
AVLTree() { // Constructor
root = NULL;
}
~AVLTree() { // Destructor
destroySubTree(root);
}
void insertNode(string n, Professor* professor);
Professor* searchNode(string);
// Call private displayInOrder()
void displayInOrder() const {
displayInOrder(root);
}
};
#endif /* AVLTree_h */
AVLTree.cpp:
#include <iostream>
#include "AVLTree.h"
using namespace std;
// Insert a node into the tree recursively
void AVLTree::insert(TreeNode *&nodePtr, TreeNode *&newNode) {
if (nodePtr == NULL) {
nodePtr = newNode;
}
else if (newNode->name < nodePtr->name) {
insert(nodePtr->left, newNode);
balance(nodePtr);
}
else {
insert(nodePtr->right, newNode);
balance(nodePtr);
}
}
// Destory the sub tree
void AVLTree::destroySubTree(TreeNode *nodePtr) {
if (nodePtr) {
if (nodePtr->left) {
destroySubTree(nodePtr->left);
}
if (nodePtr->right) {
destroySubTree(nodePtr->right);
}
delete nodePtr;
}
}
// Display the tree in order
void AVLTree::displayInOrder(TreeNode *nodePtr) const {
if (nodePtr) {
displayInOrder(nodePtr->left);
cout << nodePtr->name << endl;
displayInOrder(nodePtr->right);
}
}
// Get the tree's height
int AVLTree::height(TreeNode *temp) {
int leftHeight, rightHeight;
if (temp) {
leftHeight = height(temp->left);
rightHeight = height(temp->right);
if (leftHeight > rightHeight) {
return leftHeight + 1;
}
else if (leftHeight < rightHeight) {
return rightHeight + 1;
}
else {
return 0;
}
}
return 0;
}
// Get the difference
int AVLTree::diff(TreeNode *temp) {
int l_height = height(temp->left);
int r_height = height(temp->right);
return l_height - r_height;
}
// Balance the tree
void AVLTree::balance(TreeNode *&temp) {
int bal_factor = diff (temp);
if (bal_factor > 1)
{
if (diff(temp->left) > 0) // 2, 1 RIGHT
{
temp = r_rotation(temp);
cout << "\nRIGHT rotation";
}
else // 2, -1 LEFT-RIGHT
{
temp = lr_rotation(temp);
cout << "\nLEFT-RIGHT rotation";
}
}
else if (bal_factor < -1)
{
if (diff (temp->right) > 0) // -2, 1 RIGHT-LEFT
{
temp = rl_rotation(temp);
cout << "\nRIGHT-LEFT rotation";
}
else // -2, -1 LEFT
{
temp = l_rotation(temp);
cout << "\nLEFT Rotation";
}
}
}
// Insert a node, calls the private insert function
void AVLTree::insertNode(string n, Professor *proffesor) {
TreeNode *newNode = NULL; // Pointer to a new node.
newNode = new TreeNode;
newNode->name = n;
newNode->prof = proffesor;
newNode->left = newNode->right = NULL;
// Insert the node.
insert(root, newNode);
}
Professor* AVLTree::searchNode(string s) {
cout << "Name inputted into search: " << s << endl;
cout << endl << "Actual name: " << root->name << endl;
TreeNode *nodePtr = root;
while (nodePtr != NULL) {
if (nodePtr->name == s) {
return nodePtr->prof;
}
else if (nodePtr->name > s) {
nodePtr = nodePtr->left;
cout << "Left -> " << nodePtr << endl;
}
else {
nodePtr = nodePtr->right;
cout << "Right -> " << nodePtr << endl;
}
}
return NULL;
}
Professor.h:
#ifndef PROFESSOR_H
#define PROFESSOR_H
#include <iostream>
#include <iomanip>
using namespace std;
class Professor
{
private:
string name;
string course;
bool clearGrading;
bool goodFeedback;
bool caring;
bool reachable;
bool toughGrader;
bool lectureHeavy;
bool attendance;
public:
Professor(string n, string course, bool cG, bool gF, bool c, bool r, bool tG, bool lH, bool a) {
this->name = n;
this->course = course;
this->clearGrading = cG;
this->goodFeedback = gF;
this->caring = c;
this->reachable = r;
this->toughGrader = tG;
this->lectureHeavy = lH;
this->attendance = a;
}
friend ostream &operator << (ostream &strm, Professor &p)
{
strm << endl << endl;
strm << setw(30) << "Professor:" << setw(20) << p.name << endl;
strm << setw(30) << "Course:" << setw(20) << p.course << endl;
strm << setw(30) << "Clear Grading Criteria:" << setw(20);
if(p.clearGrading == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Provides Good Feedback:" << setw(20);
if(p.goodFeedback == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Caring:" << setw(20);
if(p.caring == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Reachable Outside of Class:" << setw(20);
if(p.reachable == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Tough Grader:" << setw(20);
if(p.toughGrader == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Lecture Heavy:" << setw(20);
if(p.lectureHeavy == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Attendance Mandatory:" << setw(20);
if(p.attendance == 0) strm << "no"; else strm << "yes";
strm << endl;
return strm;
}
};
#endif
ProfessorData.txt:
Michael Scott$CSC1310$0$0$1$1$0$1$1$Jim Halpert$CSC1310$1$1$1$0$0$0$0$Pam Beesly$CSC1300$1$1$1$0$1$0$1$Dwight Schrute$CSC2400$1$1$0$0$1$1$1$Angela Martin$CSC1300$1$0$0$0$1$1$1$Kelly Kapoor$CSC1300$0$0$0$0$0$0$0$Andy Bernard$CSC2400$1$0$1$1$0$1$1$Kevin Malone$CSC1310$0$1$1$1$0$0$0$Meredith Palmer$CSC1310$0$1$1$1$0$0$0$Phyllis Vance$CSC1300$1$1$1$0$1$0$0$Oscar Nunez$2400$1$1$1$1$1$1$1$
Running the program:
11 Proffesors have added from the file.
Which Computer Science professor do you want details about?
Andy Bernard
Angela Martin
Dwight Schrute
Jim Halpert
Kelly Kapoor
Kevin Malone
Meredith Palmer
Michael Scott
Oscar Nunez
Pam Beesly
Phyllis Vance
Type Professor Name: Andy Bernard
Name inputted into search: Andy Bernard
Actual name: Michael Scott
Left -> 0x100704570
Left -> 0x105a045b0
Left -> 0x105b04120
Left -> 0x105b041a0
Name inputted into search: Andy Bernard
Actual name: Michael Scott
Left -> 0x100704570
Left -> 0x105a045b0
Left -> 0x105b04120
Left -> 0x105b041a0
0x7ffeefbfee18Would you like to search another? (Y/N):
As you can see, I've put in some prints to kind of debug what's happening. I believe my objects are not getting inserted into the tree right, or my search function is off. Also, I'm not 100% on the balance function. Any help would be amazing.
So i am writing a programm where user fills two linked lists with integers, and now i need to create a function that creates third linked list with values from both first and second lists without duplicates.
Here is the code i have right now:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
int info;
node *next;
node (int i, node *n=NULL)
{
info = i;
next = n;
}
~node()
{
cout <<"NODE CONTAINING \"" << info << "\" WAS DELETED!" << endl;
}
};
struct list
{
node* startList1, *lastList1, *startList2, *lastList2;
int menuOption;
int nodeCount1=0, nodeCount2=0;
list() {
startList1 = NULL;
startList2 = NULL;
}
void addList1(node *p)
{
int n;
cout << "PLEASE INPUT VALUE WHICH YOU WANT IN THE NODE:";
cin >> n;
p = new node(n);
nodeCount1++;
if(startList1==NULL)
{
startList1 = lastList1 = p;
}
else
{
lastList1->next = p;
lastList1 = p;
}
}
void printList1(node *pr)
{
node *pr;
for (pr=startList1; pr!=NULL; pr=pr->next)
{
cout << pr->info << endl;
}
}
void addList2(node *q)
{
int n;
cout << "PLEASE INPUT VALUE WHICH YOU WANT IN THE NODE:";
cin >> n;
q = new node(n);
nodeCount2++;
if(startList2==NULL)
{
startList2 = lastList2 = q;
}
else
{
lastList2->next = q;
lastList2 = q;
}
}
void printList2(node *pr)
{
for (pr=startList2; pr!=NULL; pr=pr->next)
{
cout << pr->info << endl;
}
}
// this just prints first and second lists to show what is inside..
void printBoth(node *pr, node *qr)
{
cout << "Elements of the first list:" << endl;
for (pr=startList1; pr!=NULL; pr=pr->next)
{
cout << pr->info << endl;
}
cout << "Elements of the second list:" << endl;
for (pr=startList2; pr!=NULL; pr=pr->next)
{
cout << pr->info << endl;
}
}
void printMenu()
{
cout << "MENU" << endl;
cout << "(1) ADD ELEMENT LIST1." << endl;
cout << "(2) PRINT LIST1" << endl;
cout << "(3) ADD ELEMENT LIST2" << endl;
cout << "(4) PRINT LIST2" << endl;
cout << "(5) PRINT BOTH LISTS" << endl;
cout << "(6) USE MERGE FUNCTION" << endl;
cout << "(7) TO EXIT" << endl;
cin >> menuOption;
system ("cls");
};
void dragons()
{
node *temp1 = startList1;
node *temp2 = startList2;
while(temp1)
{
temp1 = startList1->next;
delete startList1;
startList1=temp1;
}
while(temp2)
{
temp2 = startList2->next;
delete startList2;
startList2=temp2;
}
};
};
int main()
{
struct node *p = NULL, *q = NULL;
list s;
s.printMenu();
node* list1;
node* list2;
node* sorting;
while(s.menuOption!=7)
{
switch (s.menuOption)
{
case 1: s.addList1(list1);
break;
case 2: s.printList1(list1);
break;
case 3: s.addList2(list2);
break;
case 4: s.printList2(list2);
break;
case 5:s.printBoth(list1, list2);
break;
case 6:s.merge();
break;
default: cout << "SOMETHING WENT WRONG!!!!" << endl;
break;
}
system ("pause");
system ("cls");
s.printMenu();
}
s.dragons();
return 0;
}
So now user can input elements to both lists and see them, but how can i create a function, that will merge those lists without duplicate values? for example:
List1 = 1, 2, 3, 6, 8;
List2 = 2, 4, 5, 7, 8;
Merged list = 1, 2, 3, 4, 5, 7, 8; (can be whatever order actually, it doesn't matter)
Any advice would be appreciated! Thanks!
Here is a version of your code, but using an STL list container to provide the linked list, and this provides its own functions that will achieve what you want. This code is for demonstration, and is not optimised for efficiency, it just shows one possible method of merging unique elements from two lists. (For this to work, the list requires its elements to be sorted, and you need to provide predicates for "less than" and "equal to" for the nodes in the list.)
(Its true that it takes time to learn some of the STL containers and functions, but many people would recommend doing that instead of trying to create your own raw-pointer-based linked list from scratch.)
Hope this helps, or is of interest.
#include <iostream>
#include <stdlib.h>
#include <list>
struct node
{
int info;
node (int i)
{
info = i;
}
~node()
{
//std::cout <<"NODE CONTAINING \"" << info << "\" WAS DELETED!" << std::endl;
}
};
bool nodeLess(node n1, node n2)
{
return n1.info < n2.info;
}
bool nodeEqual(node n1, node n2)
{
return n1.info == n2.info;
}
struct mylist
{
int menuOption;
std::list<node> list1;
std::list<node> list2;
void addList(std::list<node>& l)
{
int x;
std::cout << "PLEASE INPUT VALUE WHICH YOU WANT IN THE NODE: ";
std::cin >> x;
node n(x);
l.push_back(n);
}
void printList(const std::list<node>& l)
{
for (std::list<node>::const_iterator it = l.cbegin(); it != l.cend(); ++it)
{
std::cout << it->info << std::endl;
}
}
void addList1() { addList(list1); }
void addList2() { addList(list2); }
void printList1() { printList(list1); }
void printList2() { printList(list2); }
// this just prints first and second lists to show what is inside..
void printBoth()
{
std::cout << "Elements of the first list:" << std::endl;
printList1();
std::cout << "Elements of the second list:" << std::endl;
printList2();
}
void simpleMerge()
{
std::list<node> merged;
merged.insert(merged.end(), list1.begin(), list1.end());
merged.insert(merged.end(), list2.begin(), list2.end());
std::cout << "CONTENTS OF LIST1 THEN LIST2: " << std::endl;
printList(merged);
}
void uniqueSortMerge()
{
std::list<node> sorted1(list1.begin(), list1.end());
std::list<node> sorted2(list2.begin(), list2.end());
sorted1.sort(nodeLess);
sorted2.sort(nodeLess);
sorted1.unique(nodeEqual);
sorted2.unique(nodeEqual);
std::list<node> merged;
std::merge(sorted1.begin(), sorted1.end(),
sorted2.begin(), sorted2.end(),
std::back_inserter(merged),
nodeLess);
std::cout << "UNIQUE CONTENTS OF LIST1 AND LIST2 SORTED AND MERGED: " << std::endl;
printList(merged);
}
void printMenu()
{
std::cout << "MENU" << std::endl;
std::cout << "(1) ADD ELEMENT LIST1." << std::endl;
std::cout << "(2) PRINT LIST1" << std::endl;
std::cout << "(3) ADD ELEMENT LIST2" << std::endl;
std::cout << "(4) PRINT LIST2" << std::endl;
std::cout << "(5) PRINT BOTH LISTS" << std::endl;
std::cout << "(6) USE SIMPLE MERGE FUNCTION" << std::endl;
std::cout << "(7) USE UNIQUE, SORT AND MERGE FUNCTION" << std::endl;
std::cout << "(8) TO EXIT" << std::endl;
std::cin >> menuOption;
system ("cls");
};
void dragons()
{
list1.clear();
list2.clear();
};
};
int main()
{
mylist s;
do
{
s.printMenu();
switch (s.menuOption)
{
case 1:
s.addList1();
break;
case 2:
s.printList1();
break;
case 3:
s.addList2();
break;
case 4:
s.printList2();
break;
case 5:
s.printBoth();
break;
case 6:
s.simpleMerge();
break;
case 7:
s.uniqueSortMerge();
break;
case 8:
break;
default:
std::cout << "SOMETHING WENT WRONG!!!!" << std::endl;
break;
}
system ("pause");
system ("cls");
} while(s.menuOption != 8);
s.dragons();
return 0;
}
I need to find the largest element in the list. In the following code unsubscribed items and ordered them. How to find the last element of list? I think that I need add one more function void maksimum(), but I'm having trouble with that.
#include <iostream>
#include <string>
#include <time.h>
#include <conio.h>
#include <cstdlib>
using namespace std;
struct element
{
int number;
element* next;
element();
};
element::element()
{
next = NULL;
}
struct list
{
element* first;
void fill_list(int number);
void segregate();
void show_list();
void maksimum();
list();
};
list::list()
{
first = NULL;
}
void list::fill_list(int number)
{
element *nowy = new element;
nowy->number = number;
if(first == 0)
{
first = nowy;
}
else
{
element* temp = first;
while(temp->next)
{
temp = temp->next;
}
temp->next = nowy;
}
}
void list::show_list()
{
element* temp = first;
if(temp == 0)
{
cout << "List is empty." << endl;
cout << "No smallest element " << endl;
cout << "No largest element" << endl;
}
else
{
while(temp)
{
cout << temp->number << endl;
temp = temp->next;
}
cout << "the smallest element: : " << first->number << endl;
if(first->next == 0)
{
cout << "Largest element = Smallest element :)" << endl;
}
}
}
void list::segregate()
{
element* new_first = NULL;
element* prv;
element* temp;
element* maks;
while(first)
{
maks = first;
prv = NULL;
temp = first;
while(temp->next)
{
if(temp->next->number > maks->number)
{
prv = temp;
maks = temp->next;
}
temp=temp->next;
}
if (prv)
{
prv->next = maks->next;
}
else
{
first = maks->next;
}
maks->next = new_first;
new_first = maks;
}
first = new_first;
}
int main()
{
int n=0;
int number=0;
list* base = new list;
cout << "Size of list: " << endl;
cin >> n;
for(int i = 0; i < n; i++)
{
cout << "No " << i+1 << ": ";
cin >> number;
base->fill_list(number);
}
base->segregate();
base->show_list();
//base->maksimum();
delete(base);
return 0;
}
How can I do that?
ok. you're right, but I thought that my code shows my work. not matter :)
i solved my problem. My function: ^^
void list::show_list()
{
element * temp = first;
if( temp == 0 )
{
cout << "List is empty." << endl;
cout << "No smallest element " << endl;
cout << "No largest element" << endl;
}
else
{
while( temp->next != 0 )
{
temp = temp->next;
}
cout << "The largest element: " << temp->number << endl;
cout << "The smallest element: " << first->number << endl;
}
}
I'm having the hardest time figuring this thing out. The error is in line 58 of main.cpp, I wrote a noticeable comment on line 58.
|58|error: expected primary-expression before ';' token
Main.cpp
#include <iostream>
#include <vector>
#include "LinkedList.h"
using namespace std;
bool eic(const string &str1, const string &str2){
if(str1.length() != str2. length())
return false;
for(int i = 0; i < str1.length(); i++)
if(toupper(str1[i]) != toupper(str2[i])) return false;
return true;
}
vector<string> tokenizer(const string &str, char delim, bool emptyok)
{
vector<string> tokens;
string t;
for(int i = 0; i < str.length(); i++)
{
if (str[i] == delim)
{
if(emptyok || (t.length() != 0))
tokens.push_back(t);
t.clear();
continue;
}
t.push_back(str[i]);
}
if(emptyok || (t.length() != 0)) tokens.push_back(t);
return tokens;
}
int main(){
LinkedList<int> sList;// = LinkedList<int>;
string input;
cout << "Type 'commands' to see the list of commands" << endl;
cin >> input;
vector<string> inputV = tokenizer(input,' ',false);
while(!eic(input,"exit")){
if(eic(input,"commands")){
cout << endl;
cout << "Do not include <> in any commands" << endl;
cout << endl;
cout << "Create <name of list>: Create a new list and names it." << endl;
cout << "Print <name of list>: Prints out the entire list." << endl;
cout << "Add <name of list> <item>: Adds an element to the list." << endl;
cout << "Delete <name of list> <item>: Deletes an element from the list." << endl;
cout << "DeleteAll <name of list> <item>: Deletes all occurences of the element from the list." << endl;
cout << "MakeEmpty <name of list>: Removes all elements from the list." << endl;
cout << "Length <name of list>: Tells you how many elements are in the list" << endl;
cout << "Remove <name of list> deletes an entire list" << endl;
cout << "Exit: Terminates the program" << endl;
}
else if(eic(inputV[0],"create")){
sList = LinkedList<int>; // LINE 58 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
sList.setName(inputV[1]);
cout << sList.getName();
//cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"print")){
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"add")){
//sList->insertItem(9);
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"delete")){
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"deleteAll")){
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"makeEmpty")){
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"length")){
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"remove")){
cout << "This function is still under construction" << endl;
}
else cout << endl << "Invalid inquiry, please enter 'commands' to see a list of valid commands." << endl;
cin >> input;
}
}
If you need it here is my LinkedList.cpp file
#include <iostream>
#include "LinkedList.h"
using namespace std;
template <class xtype>
LinkedList<xtype>::LinkedList()
{
cout << "List created successfuly\n";
}
template <class xtype>
void LinkedList<xtype>::setLength(int x){
length = x;
}
template <class xtype>
int LinkedList<xtype>::getLength(){
return length;
}
template <class xtype>
void LinkedList<xtype>::setName(string x){
name = x;
}
template <class xtype>
string LinkedList<xtype>::getName(){
return name;
}
template <class xtype>
void LinkedList<xtype>::insertItem(xtype item){
node<xtype> *temp = new node<xtype>;
if(head == NULL || head->info > item){
temp->next = head;
head = temp;
}
else{
node<xtype> *q = head;
node<xtype> *p = head->next;
while(p != head && p->info <= item){
q = p;
p = p->next;
}
q->next = temp;
temp->next = p;
}
}
template class LinkedList<int>;
And the LinkedList header file
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
using namespace std;
template <class xtype>
struct node{
xtype info;
node *next;
node *prev;
};
template <class xtype>
class LinkedList
{
public:
LinkedList();
int getLength();
void setLength(int);
void setName(string);
string getName();
//bool searchItem(xtype item);
void insertItem(xtype item);
//void deleteItem(xtype item);
//int numOccur(xtype item);
protected:
private:
node<xtype> *head;
node<xtype> *term;
int length;
string name;
};
#endif // LINKEDLIST_H
Any help you can give me would be much appreciated. I'm brand new to c++, coming from java, and I've just been slaving over this all of last night up until now.
When you declare sList as LinkedList<int>, you already have invoked the default constructor to initialize sList. There's no need to assign this explicitly, as you (try to) do in the failing line.
This demonstrates a confusing but vital concept when coming from Java to C++ : RAII
I created an array for studentrecords and am supposed to pop it into my stack.. well everything works except for my stack.pops and stack.pushes in MAIN...I am so close to finishing this program I am wondering if anyone knows any solutions?
#include <iostream>
#include <list>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <string>
using namespace std;
class Studentrecords
{
private:
struct student
{
string name;
string address;
int ID;
double gpa;
};
student *stackArray;
int stackSize;
int top;
public:
Studentrecords();
Studentrecords(int size);
~Studentrecords();
void push(string name, string address, int id, double gpa);
void pop();
bool isFull() const;
bool isEmpty() const;
void display();
};
Studentrecords::Studentrecords(int size)
{
stackArray = new student[size];
top = -1;
}
Studentrecords::Studentrecords()
{
stackSize = 20;
stackArray = new student[stackSize];
top = -1;
}
Studentrecords::~Studentrecords()
{
delete [] stackArray;
}
void Studentrecords::push (string name, string address, int id, double gpa)
{
if (isFull())
{
cout << "The stack is full!" << endl;
}
else
{
student newStudent;
newStudent.name = name;
newStudent.address= address;
newStudent.ID = id;
newStudent.gpa = gpa;
stackArray[top] = newStudent;
top++;
}
}
void Studentrecords::pop ()
{
if (isEmpty())
{
cout << "The stack is empty!" << endl;
}
else
{
cout << stackArray[top-1].name << endl;
cout << stackArray[top-1].address << endl;
cout << stackArray[top-1].ID << endl;
cout << stackArray[top-1].gpa << endl;
top--;
}
}
bool Studentrecords::isFull() const
{
bool status;
if (top == stackSize - 1)
status = true;
else
status = false;
return status;
}
bool Studentrecords::isEmpty() const
{
bool status;
if (top == -1)
status = true;
else
status = false;
return status;
}
void Studentrecords::display()
{
for (int i = 0; i< top; i++)
{
cout << stackArray[i].name << endl;
cout << stackArray[i].address << endl;
cout << stackArray[i].ID << endl;
cout << stackArray[i].gpa << endl << endl;
}
}
int main()
{
int catchVar;
Studentrecords stack();
cout << "Pushing 1st";
stack.push("Jonny", "123 ave", 2343, 3.2);
cout << "pushing 2nd";
stack.push("Robby", "123 ave", 2343, 3.2);
cout << "Popping ";
stack.pop(catchVar);
cout << catchVar << endl;
cout << "Popping ";
stack.pop(catchVar);
cout << catchVar << endl;
return 0;
}
Studentrecords stack();
Does not declare a Studentrecords named stack, it declares a function named stack that returns a Studentrecords. Change it to
Studentrecords stack;
Also your class needs at least a copy constructor and assignment operator.
Can you post the compiler's error?
Or the produced output VS the expected output?
Without that, I'll have to say that your pop function doesn't take arguments and you are passing it catchVar... that would be a compiler error.