So I made a doubly linked list which stores a person's first name, last name, address and age and I am currently stuck on making a sorting algorithm for the list. So far I've managed to create 3 functions, one that adds a node to the list, one that deletes a node from the list and one which prints the list.
Here's what I have so far, the struct:
struct Node {
string First_Name;
string Last_Name;
string Address;
int age;
Node* next;
Node* prev;
} *first = 0, * last = 0;
The addToList function:
void addToList()
{
string temp = "Yes";
string First_Name;
string Last_Name;
string Address;
int age;
Node* current = first;
while (temp == "Yes") {
cout << "Enter the persons first name: ";
cin >> First_Name;
cout << "Enter the persons last name: ";
cin >> Last_Name;
cout << "Enter the persons age: ";
cin >> age;
cout << "Enter the persons address: ";
cin >> Address;
cout << "Would you like to add another person? Yes or No";
cin >> temp;
current = new Node;
current->First_Name = First_Name;
current->Last_Name = Last_Name;
current->age = age;
current->Address = Address;
if (last) last->next = current;
else first = current;
current->prev = last;
current->next = 0;
last = current;
}
return;
}
And the print list:
void printList()
{
if (!first)
{
cout << "Nothing is present in the list." << endl;
return;
}
Node* current = first;
while (current)
{
cout << current->First_Name << " " << current->Last_Name << " " << current->age << " " << current->Address << endl;
current = current->next;
}
}
My question is, how would I be able to sort the list alphabetically, I've never done sorting before...
Thank you!!
To use custom sorting for a doubly-linked list, overload operator<:
struct Person
{
std::string first;
std::string last;
std::string address;
unsigned int age;
bool operator<(const Person& p) const
{
bool is_less_than = false;
if (last == p.last)
{
is_less_than = first < p.first;
}
else
{
is_less_than = last < p.last;
}
return is_less_than;
}
};
Now you can use std::list and it will automatically sort by last name, then first. And std::list is a doubly-linked list.
To compare Persons:
Person a;
Person b;
//...
if (a < b)
{
std::cout << "Person A < Person B\n";
}
I have been learning about linked lists. I was writing the below code to print a linked list. But it just won't print the list. Can anybody help me troubleshoot?
#include<iostream>
#include "getline.h"
using namespace std;
struct Node
{
string name, dream;
Node *randomptr;
};
Node *Populating(){
cout << "Enter name(press enter to exit): ";
string name = GetLine();
if(name == "") return NULL;
Node *newOne = new Node;
cout << "enter dream: ";
string dream = GetLine();
newOne->randomptr = NULL;
return newOne;
}
void PrintNode(Node *eachnode)
{
cout << eachnode-> name<<endl;
cout << eachnode-> dream << endl;
}
Node* BuilingLinkedList(){
Node *listHead = NULL;
while(true)
{
Node *newOne = Populating();
if(newOne == NULL) break;
newOne->randomptr=listHead;
listHead = newOne;
}
return listHead;
}
void PrintList(Node *list)
{
for(Node *cur = list; cur!= NULL; cur = cur->randomptr)
PrintNode(cur);
}
int main()
{
Node *list = BuilingLinkedList();
PrintList(list);
}
Node *Populating(){
cout << "Enter name(press enter to exit): ";
string name = GetLine();
if(name == "") return NULL;
Node *newOne = new Node;
cout << "enter dream: ";
string dream = GetLine();
newOne->randomptr = NULL;
return newOne;
}
You're not doing anything with name or dream. They're read into local variables but never assigned to the new node.
So this is a doubly linked list that is supposed to hold names, address, and phone numbe and print them out. It works for the first 3 nodes then suddenly crashes after the the phone number entry on the third node. something is wrong with the pointers I believe but I have tried everything I can think of.
#include <iostream>
using namespace std;
class node
{
private:
string elem;
node* next;
node* prev;
string firstName;
string lastName;
string address;
string phoneNumber;
friend class linkedList;
};
//Linked list
class linkedList
{
public:
linkedList();
void addFrontNode(const string& e);
void addNode(const string& e);
void addNode2(node* nextloc, const string& e);
void addNode3(node* nextloc, const string& e);
void addNode4(node* nextloc, const string& e);
void print();
void search();
node* nextloc;
private:
node* head;
node* tail;
};
void linkedList::addFrontNode(const string &e)
{
node* v = new node;
string firstNameEntry;
string lastNameEntry;
string addressEntry;
string phoneNumberEntry;
cout << "Enter first name: ";
cin >> firstNameEntry;
cout << "Enter last name: ";
cin >> lastNameEntry;
cout << "Enter the address ";
cin.ignore();
getline(cin, addressEntry);
cout << "Enter a phone number ";
cin >> phoneNumberEntry;
v->elem = firstNameEntry;
v->lastName = lastNameEntry;
v->address = addressEntry;
v->phoneNumber = phoneNumberEntry;
v->next = head;
head = v;
}
void linkedList::addNode(const string &e)
{
node* v = new node;
string firstNameEntry;
string lastNameEntry;
string addressEntry;
string phoneNumberEntry;
cout << "Enter first name: ";
cin >> firstNameEntry;
cout << "Enter last name: ";
cin >> lastNameEntry;
cout << "Enter the address ";
cin.ignore();
getline(cin, addressEntry);
cout << "Enter a phone number ";
cin >> phoneNumberEntry;
v->elem = firstNameEntry;
v->lastName = lastNameEntry;
v->address = addressEntry;
v->phoneNumber = phoneNumberEntry;
v->next = tail;
tail = v;
tail->next = NULL;
}
void linkedList::addNode2(node* nextloc, const string &e)
{
node* v = new node;
string firstNameEntry;
string lastNameEntry;
string addressEntry;
string phoneNumberEntry;
cout << "Enter first name: ";
cin >> firstNameEntry;
cout << "Enter last name: ";
cin >> lastNameEntry;
cout << "Enter the address ";
cin.ignore();
getline(cin, addressEntry);
cout << "Enter a phone number ";
cin >> phoneNumberEntry;
v->elem = firstNameEntry;
v->lastName = lastNameEntry;
v->address = addressEntry;
v->phoneNumber = phoneNumberEntry;
nextloc = head -> next;
v->next = nextloc;
v->next = nextloc;
v->prev = nextloc->prev;
nextloc->prev = v;
}
void linkedList::addNode3(node* nextloc, const string &e)
{
node* v = new node;
string firstNameEntry;
string lastNameEntry;
string addressEntry;
string phoneNumberEntry;
cout << "Enter first name: ";
cin >> firstNameEntry;
cout << " Enter last name: ";
cin >> lastNameEntry;
cout << " Enter the address ";
cin.ignore();
getline(cin, addressEntry);
cout << " Enter a phone number ";
cin >> phoneNumberEntry;
v->elem = firstNameEntry;
v->lastName = lastNameEntry;
v->address = addressEntry;
v->phoneNumber = phoneNumberEntry;
v->next = nextloc;
v->prev = nextloc->prev;
nextloc->prev = v;
}
void linkedList::addNode4(node* nextloc, const string &e)
{
node* v = new node;
string firstNameEntry;
string lastNameEntry;
string addressEntry;
string phoneNumberEntry;
cout << "Enter first name: ";
cin >> firstNameEntry;
cout << " Enter last name: ";
cin >> lastNameEntry;
cout << " Enter the address ";
cin.ignore();
getline(cin, addressEntry);
cout << " Enter a phone number ";
cin >> phoneNumberEntry;
v->elem = firstNameEntry;
v->lastName = lastNameEntry;
v->address = addressEntry;
v->phoneNumber = phoneNumberEntry;
v->next = nextloc;
v->prev = nextloc->prev;
nextloc->prev->next = v;
nextloc->prev = v;
}
linkedList::linkedList() :head(NULL) {}
void linkedList::print()
{
node* v = new node;
v = head;
while (v != NULL)
{
cout << v->elem << " ";
cout << v->lastName << " ";
cout << v->address << " ";
cout << v->phoneNumber;
v = v->next;
}
}
void linkedList::search()
{
node* v = new node;
v = tail;
string lastNameSearch;
cout << "Enter a last name to search ";
cin >> lastNameSearch;
while (v != NULL)
{
if (v->lastName == lastNameSearch)
{
cout << v->elem;
cout << v->address;
cout << v->phoneNumber;
}
v = v->prev;
}
}
int main()
{
string node1;
string node2;
string node3;
string node31;
string node4;
string node5;
linkedList list;
list.addFrontNode(node1);
list.addNode(node2);
list.addNode2(list.nextloc, node3);
list.addNode3(list.nextloc, node4);
list.addNode4(list.nextloc, node5);
list.print();
return 0;
}
There are several issues.
If you use addFrontNode() to add first node, you must set your tail.
Change this:
v->next = head;
head = v;
To this:
v->next = NULL;
head = v;
tail = v;
Your function addNode() doesn't add to list correctly, try calling print and you will see, no node is added by this function.
Change this:
v->next = tail;
tail = v;
tail->next = NULL;
To this:
tail->next = v;
v->next = NULL;
tail = v;
In main() just use addFrontNode() to add first and then use addNode() to add all others. After this your code worked as expected.
Didn't understand meaning of variable nextloc, might be the source of problems.
Overall recommendation: create one function to add node
The code is indeed in need of re-write, but I don't want to repeat recommendations from the first answer. I however, believe that the question was about the reasons of the crash. It's because while copy-pasting the code, you added 2 extra lines to your addNode2:
void linkedList::addNode2(node* nextloc, const string &e)
{
...
nextloc = head -> next;
v->next = nextloc;
...
}
Comment out at least first of them and it won't crash any more (but this wouldn't make it better, really).
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 6 years ago.
I have to design a program to allow the user to input information for 5 nodes in a doubly linked list and then sort the doubly linked list alphabetically. It skips over allowing the user to input the address, doesn't print any information besides the name ,and doesn't sort the list alphabetically. What am I doing wrong?
#include <iostream>
#include <string>
struct node
{
std::string firstName;
std::string lastName;
std::string address;
long phoneNum;
node *next;
node *prev;
};
bool isEmpty(node *head);
void insertAsFirstElement(node *&head, node *&last, std::string firstName, std::string lastName, std::string address, long phoneNum);
void insert(node *&head, node *&last, std::string firstName, std::string lastName, std::string address, long phoneNum);
void searchFor(node *&last, std::string lastName);
void showList(node *current);
bool isEmpty(node *head)
{
if(head == NULL)
return true;
else
return false;
}
void insertAsFirstElement(node *&head, node *&last, std::string firstName, std::string lastName, std::string address, long phoneNum)
{
node *temp = new node;
temp->firstName = firstName;
temp->lastName = lastName;
temp->address = address;
temp->phoneNum;
temp->next = NULL;
temp->prev = NULL;
head = temp;
last = temp;
}
void insert(node *&head, node *&last, std::string firstName, std::string lastName, std::string address, long phoneNum)
{
if(isEmpty(head))
insertAsFirstElement(head, last, firstName, lastName, address, phoneNum);
else
{
node *temp = new node;
temp->firstName = firstName;
temp->lastName = lastName;
temp->address = address;
temp->phoneNum;
int result = lastName.compare(last->lastName);
if (result < 0)
{
temp->next = head;
head->prev = temp;
temp->prev = NULL;
head = temp;
}
else if ( result > 0)
{
temp->next = NULL;
temp->prev = last;
last->next = temp;
last = temp;
}
}
}
void searchFor(node *&last, std::string findName)
{
node *temp = last;
while (temp != NULL)
{
if (temp->lastName == findName)
{
std::cout << temp->firstName << " " << temp->lastName << " " << temp->address << " " << temp->phoneNum << std::endl;;
}
temp = temp->prev;
}
}
void showList(node *current)
{
if(isEmpty(current))
std::cout << "The list is empty\n";
else
{
std::cout << "The list contains: \n";
while(current != NULL)
{
std::cout << current->firstName << " " << current->lastName << " " << current->address << " " << current->phoneNum << std::endl;
current = current->next;
}
}
}
int main()
{
node *head = NULL;
node *last = NULL;
std::string firstName;
std::string lastName;
std::string address;
long phoneNum;
int count;
count = 5;
while (count > 0)
{
std::cout << "Enter the first name of person #" << count << ":\n";
std::cin >> firstName;
std::cout << "Enter the last name of person #" << count << ":\n";
std::cin >> lastName;
std::cout << "Enter the address of person #" << count << ":\n";
std::getline(std::cin,address);
std::cout << "Enter the phone number of person #" << count << ":\n";
std::cin >> phoneNum;
insert(head, last, firstName, lastName, address, phoneNum);
count = count - 1;
}
showList(head);
std::string findName;
std::cout << "What is the last name of the person you would like to find?\n";
std::cin >> findName;
searchFor(last, findName);
return 0;
}
Your issue is that you are mixing cin >> and getline which is problematic in C++ due to trailing newlines and what not.
Good practice is to always use getline and then use a stringstream to split the line up into tokens. For example, I modified your solution to only use getline and string streams (NOTE: You need to #include <sstream> at the top of your file.
You can read more about the issues with mixing cin >> and getline and also other ways to solve them here.
int main()
{
node *head = NULL;
node *last = NULL;
std::string firstName;
std::string lastName;
std::string address;
std::string phoneNumStr;
long phoneNum;
int count;
count = 5;
while (count > 0)
{
std::cout << "Enter the first name of person #" << count << ":\n";
std::getline(std::cin,firstName); // no use of cin >>
std::cout << "Enter the last name of person #" << count << ":\n";
std::getline(std::cin,lastName); // no use of cin >>
std::cout << "Enter the address of person #" << count << ":\n";
std::getline(std::cin,address);
std::cout << "Enter the phone number of person #" << count << ":\n";
std::getline(std::cin,phoneNumStr);
std::stringstream s(phoneNumStr); // no use of cin. Using stringstream to break up line and extract it into phoneNum
s >> phoneNum;
insert(head, last, firstName, lastName, address, phoneNum);
count = count - 1;
}
showList(head);
std::string findName;
std::cout << "What is the last name of the person you would like to find?\n";
std::cin >> findName;
searchFor(last, findName);
return 0;
}
I've started c++ programming 5weeks back.
I'm working on a program and using linkedlists to store data in the program. So for this is what I'm done and the program is not compiling. I will be glad if the community gives some idea in fixing these errors.
// C++ Assignment.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// Global variables
string name;
int nic;
int contact;
string address;
int customerId;
string status;
string todaysVehicle;
string vnum;
string serviceType;
int GetInput()
{
int choice;
cin >> choice;
return choice;
}
struct list
{
string name;
int nic;
int contact;
string address;
int customerId;
string status;
string todaysVehicle;
string vnum;
string serviceType;
list *next;
};
// List Function Prototypes
bool empty(list *head);
void DisplayMenu();
void firsttElement(list *&head, list *&last, int nic, string name, int contact, string address, int customerId, string todaysVehicle, string vnum);
void insertCusomter(list *&head, list *&last, int nic, string name, int contact, string address, int customerId, string todaysVehicle, string vnum);
void removeCustomer(list *&head, list *&last, int nic, string name, int contact, string address, int customerId, string todaysVehicle, string vnum);
void customerList(list *current);
bool empty(list *head){
if (head == NULL)
return true;
else
return false;
}
// Main menu of the program
void DisplayMenu(){
}
void firstElement(list *&head, list *&last, int nic, string name, int contact, string address, int customerId, string todaysVehicle, string vnum){
list *temp1 = new list;
temp1->nic = nic;
temp1->next = NULL;
head = temp1;
last = temp1;
list *temp2 = new list;
temp2->name = name;
temp2->next = NULL;
head = temp2;
last = temp2;
list *temp3 = new list;
temp3->nic = contact;
temp3->next = NULL;
head = temp3;
last = temp3;
list *temp4 = new list;
temp4->address = address;
temp4->next = NULL;
head = temp4;
last = temp4;
list *temp5 = new list;
temp5->nic = customerId;
temp5->next = NULL;
head = temp5;
last = temp5;
list *temp6 = new list;
temp6->todaysVehicle = todaysVehicle;
temp6->next = NULL;
head = temp6;
last = temp6;
list *temp7 = new list;
temp7->vnum = vnum;
temp7->next = NULL;
head = temp7;
last = temp7;
}
void insertCustomer(list *&head, list *&last, int nic, string name, int contact, string address, int customerId, string todaysVehicle, string vnum){
if (empty(head))
firstElement(head, last, nic, name, contact, address, customerId, todaysVehicle, vnum);
else {
list *temp = new list;
temp->nic = nic;
temp->next = NULL;
last->next = temp;
last = temp;
}
if (empty(head))
firstElement(head, last, nic, name, contact, address, customerId, todaysVehicle, vnum);
else {
list *temp = new list;
temp->name = name;
temp->next = NULL;
last->next = temp;
last = temp;
}
if (empty(head))
firstElement(head, last, nic, name, contact, address, customerId, todaysVehicle, vnum);
else {
list *temp = new list;
temp->address = address;
temp->next = NULL;
last->next = temp;
last = temp;
}
if (empty(head))
firstElement(head, last, nic, name, contact, address, customerId, todaysVehicle, vnum);
else {
list *temp = new list;
temp->nic = contact;
temp->next = NULL;
last->next = temp;
last = temp;
}
if (empty(head))
firstElement(head, last, nic, name, contact, address, customerId, todaysVehicle, vnum);
else {
list *temp = new list;
temp->nic = customerId;
temp->next = NULL;
last->next = temp;
last = temp;
}
if (empty(head))
firstElement(head, last, nic, name, contact, address, customerId, todaysVehicle, vnum);
else {
list *temp = new list;
temp->todaysVehicle = todaysVehicle;
temp->next = NULL;
last->next = temp;
last = temp;
}
if (empty(head))
firstElement(head, last, nic, name, contact, address, customerId, todaysVehicle, vnum);
else {
list *temp = new list;
temp->vnum = vnum;
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void removeCustomer(list *&head, list *&last){
if (empty(head))
cout << "There are no Customers in the Database! \n";
else if (head == last){
delete head;
head = NULL;
last = NULL;
}
else{
list *temp = head;
head = head->next;
delete temp;
}
}
void customerList(list *current){
if (empty(current))
cout << "The list is empty \n;";
else
{
cout << "The list contains: \n";
while (current != NULL){
cout << current->customerId << endl;
cout << current->nic << endl;
cout << current->name << endl;
cout << current->vnum << endl;
cout << current->todaysVehicle << endl;
cout << current->vnum << endl;
cout << current->contact << endl;
current = current->next;
}
}
}
// Main Fucntion
int main(int argc, _TCHAR* argv[], void insertCustomer(list *&head, list *&last, int nic, string name, int contact, string address, int customerId, string todaysVehicle, string vnum), void removeCustomer(list *&head, list *&last), void customerList(list *current)){
list *head = NULL;
list *last = NULL;
int choice;
do{
system("cls");
cout << "Clean Park Daily Car Services\n";
cout << "******************************\n";
cout << "Please make your selection\n";
cout << " \n";
cout << "1 - Register Customer\n";
cout << "2 - Request for Serivce\n";
cout << "3 - UnRegister Customer\n";
cout << "4 - Update Customer\n";
cout << "5 - View Customer\n";
cout << "6 - View all Customers\n";
cout << "7 - Exit\n";
cout << "\n";
cout << "Choice: ";
cin >> choice;
DisplayMenu();
switch (choice){
case 1: // Register a new customer
system("CLS");
cout << "PLease enter Customer National Id: \n";
cin >> nic;
cout << " Enter Customer Name: \n";
cin >> name;
cout << "Enter Customer Contact Number: \n";
cin >> contact;
cout << "Enter Customer Address: \n";
cin >> address;
cout << "Enter Customer Number: \n";
cin >> customerId;
cout << "Enter Vehicle's Date: \n";
cin >> todaysVehicle;
cout << "Enter Vehicle Number: \n";
cin >> vnum;
void insertCustomer(list *&head, list *&last, int nic, string name, int contact, string address, int customerId, string todaysVehicle, string vnum);
break;
case 2: // Request for Service
system("CLS");
case 3: // Remove customer
system("CLS");
removeCustomer(*&head, *&last);
break;
case 4: // Update customer
system("CLS");
case 5: // View Customer
system("CLS");
case 6: // View All Customers
system("CLS");
void customerList(list *current);
break;
case 7: // Exit Application
cout << "Goodbye!.." << endl;
exit(0);
default:
cout << "System exit \n";
}
} while (choice != 7);
return 0;
}
First of all there is already a type list in namespace std. If you using namespace std; you can't declarate at type named list. You never should name any of your own types list and stay away from using namespace std.
Rename your type listto mylist, for example. Adapt your code like this:
...
struct mylist;
mylist *next;
...
struct mylist
{
...
};
bool empty(mylist *head);
...
void firstElement(myList *&head, myList *&last, int nic, string name, int contact, string address, int customerId, string todaysVehicle, string vnum){
head = last = new myList;
head->next = NULL;
head->nic = nic;
head->contact = contact;
head->address = address;
head->customerId = customerId;
head->name = name;
head->todaysVehicle = todaysVehicle;
head->vnum = vnum;
head->status = status;
head->serviceType = serviceType;
}
void insertCustomer(myList *&head, myList *&last, int nic, string name, int contact, string address, int customerId, string todaysVehicle, string vnum){
if (empty(head))
firstElement(head, last, nic, name, contact, address, customerId, todaysVehicle, vnum);
else {
last->next = new myList;
last = last->next;
last->next = NULL;
last->nic = nic;
last->contact = contact;
last->address = address;
last->customerId = customerId;
last->name = name;
last->todaysVehicle = todaysVehicle;
last->vnum = vnum;
last->status = status;
last->serviceType = serviceType;
}
}
Apart from this I recommend to use std::list and not to do it your own.