Reputation: 32
When I call the methods to print the data stored in the nodes of my doubly linked list, nothing prints except for empty strings and 0's
#include <iostream>
#include <string>
using namespace std;
struct node {
int weight;
string name;
node *nextname, *nextweight;
};
node *namehead = NULL, *weighthead = NULL;
bool isEmpty()
{
if (namehead == NULL && weighthead == NULL)
return true;
else
return false;
}
void addperson(int w, string n)
{
node* newNode = new node;
node *prev, *curr = newNode;
if (isEmpty()) {
namehead = newNode;
weighthead = newNode;
}
else {
curr = prev = namehead;
if (curr->name > n) {
namehead = newNode;
newNode->nextname = curr;
}
else {
do {
if (curr->name <= n) {
prev = curr;
curr = curr->nextname;
}
else
break;
} while (curr != NULL);
prev->nextname = newNode;
newNode->nextname = curr;
}
curr = prev = weighthead;
if (curr->weight > w) {
weighthead = newNode;
newNode->nextweight = curr;
}
else {
do {
if (curr->weight <= w) {
prev = curr;
curr = curr->nextweight;
}
else
break;
} while (curr != NULL);
prev->nextweight = newNode;
newNode->nextweight = curr;
}
}
}
void printname()
{
node* curr = namehead;
do {
cout << curr->name << " - " << curr->weight << endl;
curr = curr->nextname;
} while (curr != NULL);
cout << endl;
}
void printweight()
{
node* curr = weighthead;
do {
cout << curr->name << " - " << curr->weight << endl;
curr = curr->nextweight;
} while (curr != NULL);
cout << endl;
}
int main()
{
int w = 0;
string n;
for (int i = 0; i < 15; i++) {
cout << "Enter weight: ";
cin >> w;
if (w == -1)
break;
cout << "Enter name: ";
cin >> n;
addperson(w, n);
}
printname();
printweight();
return 0;
}
Expected output (By name):
John - 220
Steven - 190
Tyler - 150
Expected output (By weight):
Tyler - 150
Steven - 190
John - 220
CURRENT OUTPUT(Both ways):
" " - 0
" " - 0
" " - 0
EDIT By taking the suggestions in the comments about actually assigning the values w (weight) and n (name) to the temporary node in the add method, the problem has been fixed. Thank you for the help.
curr->weight=w;
curr->name=n;
Upvotes: 0
Views: 117
Reputation: 32
Assign passed values into weight and name members into placeholder node in the add method:
curr->weight=w;
curr->name=n;
Upvotes: 1