Stacks and Queues - c++

good day. i have a problem with my program. this is designed for small clinics to basically
record the patients information for an appointment. so here is my problem, at first it was
working but whenever im going to input infos for the 3rd patient(3rd node), after inputting
the name it will go on an error. this is a queue. `
#include <iostream>
using namespace std;
struct clnc_hrs
{
std:: string name;
std:: string symptms;
int age;
int cont_num;
clnc_hrs *next;
};
class List{
private:
clnc_hrs *rear;
clnc_hrs *front;
public:
List();
void BookAppointment();
void DeletePrevious();
void DisplaySchedule();
};
List::List(){
rear = NULL;
front = NULL;
}
void List::BookAppointment ()
{
std:: string N;
std:: string S;
int A;
int CN;
clnc_hrs *newnode = (clnc_hrs*)malloc(sizeof(clnc_hrs));
fflush(stdin);
cout<<"enter name of the patient:";
std::getline(cin, N);
newnode->name = N;
fflush(stdin);
cout<<"enter age of the patient:";
cin>>A;
newnode->age = A;
fflush(stdin);
cout<<"enter contact number of the patient:";
cin>>CN;
newnode->cont_num = CN;
fflush(stdin);
cout<<"enter the complaints or symptoms of the patient:";
std::getline(cin, S);
newnode->symptms = S;
newnode->next = NULL;
if(front == NULL)
{
fflush(stdin);
front = newnode;
fflush(stdin);
}
else
{
fflush(stdin);
rear->next = newnode;
fflush(stdin);
}
rear = newnode;
}
void List::DisplaySchedule ()
{
clnc_hrs *disp = (clnc_hrs*)malloc(sizeof(clnc_hrs));
disp = front;
if(front == NULL)
{
cout<<"there's no appointment for today"<<endl;
}
else
{
while(disp != NULL)
{
cout<<endl;
cout<<"name:"<<disp->name<<endl;
cout<<"age:"<<disp->age<<endl;
cout<<"contact number:"<<disp->cont_num<<endl;
cout<<"symptoms/complaints:"<<disp->symptms<<endl;
cout<<endl;
disp = disp->next;
}
}
}
void List::DeletePrevious()
{
clnc_hrs *newnode = (clnc_hrs*)malloc(sizeof(clnc_hrs));
if(front == NULL)
{
cout<<"no appointments today"<<endl;
}
else
{
newnode = front;
front = front->next;
cout<<"The previous patient is: "<<endl;
cout<<newnode->name<<endl;
cout<<newnode->age<<endl;
cout<<newnode->cont_num<<endl;
cout<<newnode->symptms<<endl;
delete newnode;
}
}
int main ()
{
List list;
int ans;
while(true)
{
cout<<"press 1 for booking an appointment\npress 2 to delete previous patients info \npress 3 for display"<<endl;
cin>>ans;
if(ans == 1)
{
list.BookAppointment();
}
else if(ans == 2)
{
list.DeletePrevious();
}
else if(ans == 3)
{
list.DisplaySchedule();
}
}
system("pause");
}
`
i hope someone here can help me. i am using dev c++ 4.9.9.2

As you say this in not homework then just use STL - i.e. http://www.cplusplus.com/reference/queue/queue/
All the bits'n'bobs are done for you

Don't use malloc in a C++ program, it doesn't construct C++ objects correctly, use new instead.
clnc_hrs *newnode = new clnc_hrs();
You might have other errors but this is the first one.
cout<<"enter name of the patient:";
std::getline(cin, N);
newnode->name = N;
is not wrong, but just a bit wasteful. This is simpler
cout<<"enter name of the patient:";
std::getline(cin, newnode->name);
same for all you other inputs.
fflush(stdin);
is implementation defined behaviour. fflush only has defined behaviour on output streams not input streams. You seem to be using fllush(stdin); as some sort of magic incantation that you hope will solve your problems. Avoid that kind of thinking. Learn what the code you write really does. In this case you should remove all calls to fflush(stdin);.

Related

How to sort nodes from a stack and put into a queue

im trying to implement both queue and stack in my mini project. Customer will enter nodes into stack and the seller will sort the nodes from stack and put them into queue. I want to sort nodes from a stack based on college name, where all nodes with college = "kdoj" will get into the queue first then followed by all nodes with college = "kdse". The problem is i have tried doing the sorting with 2 (for loop) and i dont know why only 2 nodes get into the queue when i have more than 2 nodes in the stack. i am not sure where is the problem and been stuck here for a while :(.
This is the input example:
name : david
ic num: 123
phone num: 123
college: kdse
quantity: 1
size: m
name : jojo
ic num: 123
phone num: 123
college: kdse
quantity: 1
size: m
name : zoro
ic num: 123
phone num: 123
college: kdoj
quantity: 1
size: m
This is the runnable code.
The problem will occur when you sort the list in seller menu after entering the data.
#include <iostream>
#include <cstring>
#include<iomanip>
#include <conio.h>
#include<string>
using namespace std;
//nodes
struct customerNode {
string name, id, college;
int phoneNum,quantity;
char size;
public:
customerNode* next;
customerNode(string name, string id, int phoneNum,string college, int quantity, char size)
{
name = name;
id = id;
phoneNum = phoneNum;
college = college;
quantity = quantity;
size = size;
next = NULL;
}
};
//class customer
class Customer{
public:
customerNode *head = NULL;
bool isEmpty(){
return(head == NULL);
}
void pushStack(string name, string id, int phoneNum, string college, int quantity, char size){
customerNode *newnode = new customerNode(name,id,phoneNum,college,quantity,size);
newnode->name = name;
newnode->id= id;
newnode->phoneNum = phoneNum;
newnode->college = college;
newnode->quantity = quantity;
newnode->size = size;
if(isEmpty()){
newnode->next = head;
head = newnode;
cout<<endl<<"created new stack."<<endl;
}
else{
newnode->next = head;
head = newnode;
cout<<endl<<"added node into a stack."<<endl;
}
}
//pop out node from stack
void popStack(){
customerNode *temp;
temp = head; //temp variable
head = temp->next;
temp->next = NULL;
cout<<endl<<"Order has been deleted!";
}
//push node into stack
void enterOrder(){
int phoneNum, quantity;
char size;
string name, id, college;
cout<<endl<<"\tADDING YOUR ORDER.\n";
cout<<"\tName: ";
cin.ignore();
getline(cin,name);
cout<<"\tIC Num: ";
cin>>id;
cout<<"\tPhone Number: ";
cin>>phoneNum;
cout<<"\tCollege name: ";
cin>>college;
cout<<"\tQuantity: ";
cin>>quantity;
cout<<"\tSize (S/M/L/XL): ";
cin>>size;
pushStack(name, id, phoneNum,college, quantity, size);
cin.get();
}
//see order and trigger popout funct
void deleteorder(){
char choice;
cout<<"YOUR ODER."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
stackTop();
cout<<endl;
cout<<endl<<"Confirm to delete?: ";
cin>>choice;
if(choice == 'y' || choice == 'Y'){
popStack();
}
}
//display node at the top
void stackTop(){
customerNode *check;
if(!isEmpty()){
check = head;
cout<<endl<<
setw(10)<<left<<check->id
<<setw(20)<<left<<check->name
<<setw(10)<<left<<check->phoneNum
<<setw(20)<<left<<check->college
<<setw(10)<<left<<check->quantity
<<setw(5)<<left<<check->size;
}
else{
cout<<endl<<"Stack is an underflow.";
getch();
}
}
int getNumberNodes(){
customerNode *check;
check = head;
int counter = 0;
while(check!= NULL){
counter++;
check = check->next;
}
return counter;
}
};
//Customer main menu
void customerMenu(Customer &c){
int choice;
do{cout
<<endl<<"CUSTOMER MENU"
<<endl<<"Please choose your task."
<<endl<<"1. Insert Order"
<<endl<<"2. Delete Order"
<<endl<<"3. Check Order"
<<endl<<"4. Exit"
<<endl<<"Your Choice: ";
cin>>choice;
//customer task
switch(choice){
case 1: c.enterOrder();
break;
case 2: c.deleteorder();
break;
case 3:
cout<<"\nYOUR ODER."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
c.stackTop();
cout<<endl;
break;
}
}while(choice != 4);
};
//SELLER CLASS
class Seller{
string id;
string password;
public:
customerNode *backPtr, *frontPtr;
//constructor seller
Seller(){
id = "12345";
password = "12345";
backPtr = NULL;
frontPtr = NULL;
}
//check queue empty
bool queueEmpty(){
return (backPtr == NULL && frontPtr == NULL);
}
//display all nodes in stack
void getStack(Customer &c){
customerNode *check;
if(!c.isEmpty()){
check = c.head;
while(check!=NULL){
cout<<endl<<
setw(10)<<left<<check->id
<<setw(20)<<left<<check->name
<<setw(10)<<left<<check->phoneNum
<<setw(20)<<left<<check->college
<<setw(10)<<left<<check->quantity
<<setw(5)<<left<<check->size;
check=check->next;
}
}
else{
cout<<endl<<"Stack is an underflow.";
getch();
}
}
//will trigger getStack()
void displayStack(Customer &c){
cout<<"\nCUSTOMER FULL ORDERLIST."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
getStack(c);
cout<<endl;
}
//display all nodes in queue
void getQueue(){
customerNode *check;
if(!queueEmpty()){
check = frontPtr;
while(check!=NULL){
cout<<endl<<
setw(10)<<left<<check->id
<<setw(20)<<left<<check->name
<<setw(10)<<left<<check->phoneNum
<<setw(20)<<left<<check->college
<<setw(10)<<left<<check->quantity
<<setw(5)<<left<<check->size;
check=check->next;
}
}
else{
cout<<endl<<"Stack is an underflow.";
getch();
}
}
//display node in queue
void displayQueue(){
cout<<"\nSORTED CUSTOMER FULL ORDERLIST."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
getQueue();
cout<<endl;
}
//insert queuee
void insertQueue(customerNode *newNode){
if(!queueEmpty()){
newNode->next = NULL;
backPtr->next = newNode;
backPtr = newNode;
cout<<endl<<"inserted node into queue."<<endl;
}
else{
frontPtr = newNode;
backPtr = newNode;
}
}
void sortOrder(Customer &c){
for(customerNode *node = c.head; node!=NULL; node = node->next){
if(node->college == "kdoj"){
cout<<endl<<node->college;
insertQueue(node);
}
}
for(customerNode *node = c.head; node!=NULL; node = node->next){
if(node->college == "kdse"){
cout<<endl<<node->college;
insertQueue(node);
}
}
displayQueue();
}
};
//seller main menu
void sellerMenu(Customer &c, Seller &s){
int choice;
do{cout
<<endl<<"SELLER MENU"
<<endl<<"Please choose your task."
<<endl<<"1. Display OrderList"
<<endl<<"2. Sort OrderList"
<<endl<<"4. Exit"
<<endl<<"Your Choice: ";
cin>>choice;
//choose task
switch(choice){
case 1: s.displayStack(c);
break;
case 2: s.sortOrder(c);
break;
case 3:
break;
}
}while(choice != 4);
}
void menu(Customer &c, Seller &s){ //main menu function
int choice;
do{
cout
<<endl<<"Welcome to HotspotPrinting!"
<<endl<<"Please choose your role."
<<endl<<"1. Customer"
<<endl<<"2. Seller"
<<endl<<"3. Exit"
<<endl<<"Your Choice: ";
cin>>choice;
switch(choice){
case 1: customerMenu(c);
break;
case 2: sellerMenu(c,s);
break;
}
}while(choice != 3);
}
int main()
{
Customer c;
Seller s;
menu(c,s);
cout<<endl<<"Thank You For Using Our Service :)!";
return 0;
}
your problem is that customer node records exist in two containers, your queue and a list. But you only have one next pointer, when you insert a customer into the queue you set its next pointer to null, this destroys the linkage in the customer list.
If you need to have the same object in 2 containers then use shared_ptr in standard containers, like std::list and std::queue

I'm trying to implement a binary tree. My program stops abruptly after a few node insertions. What is going wrong?

I'm just trying out implementation of binary tree. It's not for a college class so I cannot ask a teacher :(
I have tried debugging it with the Codeblocks debugger but I'm still not understanding what is going wrong.
I am using class instead of struct. Currently I have only implemented insertion and inorder traversal functions.
For insertion function, I am checking if the root node is NULL or not. If it is NULL, the newNode becomes equal to the root node. Or else, I find the appropriate parent node and then append the newNode as its child.
And, in the inorder traversal function, is my recursion correct?
Edit: Turns out that I wasn't initializing my Node variables. My code is working after initializing those variables. Thanks for your help!
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node* left_child;
Node* right_child;
};
Node* root = NULL;
void insertion();
void inorder_travesal(Node*);
int main(){
char ch;
do{
int choice;
cout<<"\nEnter your choice: \n1. Insertion\n2. Inorder Traversal\n : ";
cin>>choice;
switch(choice){
case 1: insertion();
break;
case 2: inorder_travesal(root);
break;
}
cout<<"\nDo you want to continue?: ";
cin>>ch;
}while(ch == 'y');
return 0;
}
void insertion(){
int data;
cout<<"\nEnter data: ";
cin>>data;
Node* newNode = new Node;
newNode->data = data;
if(root == NULL)
{
root = newNode;
return;
}
else
{
Node* temp = root;
while(true){
if(temp->data > newNode->data)
{
if(temp->left_child == NULL)
{
temp->left_child = newNode;
return;
}
else
{
temp = temp->left_child;
}
}
else
{
if(temp->right_child == NULL)
{
temp->right_child = newNode;
return;
}
else
{
temp = temp->right_child;
}
}
}
}
inorder_travesal(root);
}
void inorder_travesal(Node* temp){
if(temp->left_child != NULL){
inorder_travesal(temp->left_child);
}
cout<<temp->data<<" ";
if(temp->right_child != NULL){
inorder_travesal(temp->right_child);
}
}

my CLL program in C++ wont stop looping! why? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I wrote a program using single CLL in order to have the following output:
Main Menu
Create Books CLL
Add book
Search (by Book Name)
Delete Author
Enter your Choice: 1
Enter Book ID: 11223344
Enter Book Name: Programming C++
Enter Author’s Name: Jhone
Node Created
But when i enter the first choice i will enter the book id, book name and then it will start looping without stop! What's wrong with my program?
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node
{
int bid;
char book,author;
struct node *next;
}*last;
class circular_llist
{
public:
void create_node(int id,char bname,char aname);
void add_begin(int id,char bname,char aname);
void delete_element(char author);
void search_element(char name);
void display_list();
circular_llist()
{
last = NULL;
}
};
int main()
{
int choice, bid, position;
char name,author;
circular_llist cl;
while (1)
{
cout<<endl<<"Main Menu:"<<endl;
cout<<"1.Create Node"<<endl;
cout<<"2.Add at beginning"<<endl;
cout<<"3.Delete"<<endl;
cout<<"4.Search"<<endl;
cout<<"5.Display"<<endl;
cout<<"6.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter the Book ID: ";
cin>>bid;
cout<<"Enter the Book Name: ";
cin>>name;
cout<<"Enter the Book Author: ";
cin>>author;
cl.create_node(bid,name,author);
cout<<endl;
break;
case 2:
cout<<"Enter the Book ID: ";
cin>>bid;
cout<<"Enter the Book Name: ";
cin>>name;
cout<<"Enter the Book Author: ";
cin>>author;
cl.add_begin(bid,name,author);
cout<<endl;
break;
case 3:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the Author name for deletion: ";
cin>>author;
cl.delete_element(author);
cout<<endl;
break;
case 4:
if (last == NULL)
{
cout<<"List Empty!! Can't search"<<endl;
break;
}
cout<<"Enter Book Name: ";
cin>>name;
cl.search_element(name);
cout<<endl;
break;
case 5:
cl.display_list();
break;
case 6:
exit(1);
}
}
return 0;
}
void circular_llist::create_node(int id,char bname,char aname)
{
struct node *temp;
temp = new(struct node);
temp->bid = id;
temp->book = bname;
temp->author = aname;
if (last == NULL)
{
last = temp;
temp->next = last;
}
else
{
temp->next = last->next;
last->next = temp;
last = temp;
}
}
void circular_llist::add_begin(int id,char bname,char aname)
{
if (last == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->bid = id;
temp->book = bname;
temp->author = aname;
temp->next = last->next;
last->next = temp;
}
void circular_llist::delete_element(char author)
{
struct node *temp, *s;
s = last->next;
if (last->next == last && last->author == author)
{
temp = last;
last = NULL;
free(temp);
return;
}
if (s->author == author) /*First Element Deletion*/
{
temp = s;
last->next = s->next;
free(temp);
return;
}
while (s->next != last)
{
/*Deletion of Element in between*/
if (s->next->author == author)
{
temp = s->next;
s->next = temp->next;
free(temp);
cout<<"Element "<<author;
cout<<" deleted from the list"<<endl;
return;
}
s = s->next;
}
if (s->next->author == author)
{
temp = s->next;
s->next = last->next;
free(temp);
last = s;
return;
}
cout<<"Element "<<author<<" not found in the list"<<endl;
}
void circular_llist::search_element(char name)
{
struct node *s;
int counter = 0;
s = last->next;
while (s != last)
{
counter++;
if (s->book == name)
{
cout<<"Element "<<name;
cout<<" found at position "<<counter<<endl;
return;
}
s = s->next;
}
if (s->book == name)
{
counter++;
cout<<"Element "<<name;
cout<<" found at position "<<counter<<endl;
return;
}
cout<<"Element "<<name<<" not found in the list"<<endl;
}
void circular_llist::display_list()
{
struct node *s;
if (last == NULL)
{
cout<<"List is empty, nothing to display"<<endl;
return;
}
s = last->next;
cout<<"Books List: "<<endl;
while (s != last)
{
cout<<s->bid<<"\n"<<s->book<<"\n"<<s->author<<"\n"<<endl;
s = s->next;
}
cout<<s->bid<<"\n"<<s->book<<"\n"<<s->author<<"\n"<<endl;
}
When you read single characters (like you do with name and author) you really read only single character. And you enter multiple characters for those fields, meaning that the first input (to name) will read the fist character of the name, and the second input (to author) will read the second character of the name. That will leave quite a few characters in the input buffer, and attempting to read anything but characters or strings will fail, but you don't check for these failures so you end up with just looping over and over again trying to read e.g. a number and failing.
Simplest solution? Begin with using std::string for strings, and continue with reading multiple-word entries using std::getline.
The problem is how you input author and book name, e.g., cin>>name. This reads only the first word from the input and the rest of the name (if it has spaces) is left in the input buffer. Next you try to read the menu choice number and it will fail because the next character in the buffer is the first character of the second word of the name of the book, or such. I suggest that you replace your cin >> name with std::getline.
UPDATE
Oh! I have missed that you actually input only a single character...

How do I transfer some data from one node to another in C++ Linkedlist Queue?

I am sorry for posting the entire code, but I am having a real hard time while getting specific data from each node and transfer the entire data to a whole new node in the function named "Enqueue". I tried adding a watcher to see what my program is doing, it gets stuck in the "Enqueue" function at the if-statement "if (front == NULL && rear == NULL)". Can someone please point my problem what is my mistake? Thanks.
#include <iostream>
#include <string>
using namespace std;
int numb_persons_category1 = 0;
int numb_persons_category2 = 0;
int numb_persons_category0 = 0;
class Queue
{
struct node
{
string name, date;
int room;
node *next;
};
node *front;
node *rear;
public:
Queue()
{
front = NULL;
rear = NULL;
}
void Enqueue(string _name, string _date, int _room)
{
node *p = new node;
p -> name = _name;
p -> date = _date;
p -> room = _room;
p -> next = NULL;
if (front == NULL && rear == NULL)
{
front = rear = p;
return;
}
rear->next = p;
rear = p;
}
void Dequeue()
{
node *temp = front;
if (front == NULL)
return;
if (front == rear)
{
front = rear = NULL;
}
else
{
front = front->next;
}
free(temp);
}
int Front()
{
if(front == NULL)
{
cout<<"Queue is empty\n";
}
return front->room;
}
bool IsEmpty()
{
return front == NULL;
}
void populate(Queue *any_queue, int _room, int numb_persons_category)
{
node *any_node = front;
while(any_node != NULL)
{
if (_room == 1)
{
any_queue->Enqueue(any_node->name, any_node->date, any_node->room);
cout<<"Name: "<<any_node->name<<endl;
cout<<"Last Visit: "<<any_node->date<<endl;
cout<<"Room: "<<any_node->room<<endl;
cout<<any_node->name<<" must be sent to "<<_room<<endl;
numb_persons_category++;
}
else if (_room == 2)
{
any_queue->Enqueue(any_node->name, any_node->date, any_node->room);
cout<<"Name: "<<any_node->name<<endl;
cout<<"Last Visit: "<<any_node->date<<endl;
cout<<"Room: "<<any_node->room<<endl;
cout<<any_node->name<<" must be sent to "<<_room<<endl;
numb_persons_category++;
}
else if (_room == 0)
{
any_queue->Enqueue(any_node->name, any_node->date, any_node->room);
cout<<"Name: "<<any_node->name<<endl;
cout<<"Last Visit: "<<any_node->date<<endl;
cout<<"Room: "<<any_node->room<<endl;
cout<<any_node->name<<" must be sent to "<<_room<<endl;
numb_persons_category++;
}
cout<<endl<<endl;
any_node = any_node->next;
}
}
void Print()
{
//If you are using Windows, uncomment the line of code that says system("cls");
//I have added the line of code as comment since I am using a non-Windows machine.
//system("cls");
//It doesn't matter if you don't really care about the output of my program anyway
//It works in both cases.. But I am just trying to clear things up for the user :)
node* temp = front;
while(temp != NULL) {
cout<<"Name: "<<temp->name<<endl;
cout<<"Last Visit: "<<temp->date<<endl;
cout<<"Room: "<<temp->room<<endl;
cout<<endl;
temp = temp->next;
}
cout<<endl;
cout<<"Number of patients in category 0: "<<numb_persons_category0<<endl;
cout<<"Number of patients in category 1: "<<numb_persons_category1<<endl;
cout<<"Number of patients in category 2: "<<numb_persons_category2<<endl;
}
};
Queue *obj_category1;
Queue *obj_category2;
Queue *obj_category0;
void room(string _name, string _date, int _room, Queue *obj)
{
switch (_room)
{
case 1:
obj->populate(obj_category1, _room, numb_persons_category1);
break;
case 2:
obj->populate(obj_category2, _room, numb_persons_category2);
cout<<_name<<" must be sent to "<<_room<<endl;
numb_persons_category2++;
break;
case 0:
obj->populate(obj_category0, _room, numb_persons_category0);
cout<<_name<<" must be sent to "<<_room<<endl;
numb_persons_category0++;
break;
default:
cout<<"Room is unavailable!\n\n";
}
}
int main()
{
Queue *obj = new Queue();
int room_number;
string name, date;
char user_visit;
char run = 'y';
while (run == 'y')
{
cout<<"Enter name: ";
cin>>name;
cout<<"Is this your first visit? (Y/N): ";
cin>>user_visit;
if (user_visit == 'n')
{
cout<<"Enter your last visit (MM/DD/YY): ";
cin>>date;
}
else
{
date = "0/0/0";
}
cout<<"Enter room: ";
cin>>room_number;
cout<<"\n\n\n";
obj->Enqueue(name, date, room_number);
room(name, date, room_number, obj);
cout<<"Continue? (Y/N): ";
cin>>run;
}
return 0;
}
You are allocating nodes with new and deallocating them with free.
At least that's one of the bugs, there might be more. Try stepping
through
your code with a debugger.
note; new goes with delete, and is preferable in C++
malloc goes with free and is C-style
First, please indent the entire program code, not only the nested blocks.
Second, you have:
Queue *obj_category1; // which is null as global var initialized by default
obj->populate(obj_category1, _room, numb_persons_category1); // here you pass that null pointer and then it is accessed in the line the debugger complaining about
And yes, 'new' should be matched with 'delete' not 'free' as it was correctly pointed out already. But that is not the reason for specific error and will trigger the error if specific destructor not called. That is not nice in this case but not lethal.

new nodes always becomes the first node in my single linkedlist [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been learning the implementation of single linked list in c++.
Thing is that I understood the concept behind single linked list but I am not able to guess where I have done mistake in the code.
Whenever I insert a new node, it takes the first position (i.e head) and the size of the list is always 1.
I tried to solve it but sometimes display function turns into infinite loop.
I am getting no clue on this.
Its been pricking my mind for a week.
All I can guess is, I am not referencing the addresses properly in the code.
Am I messing up with the pointers? Help by making me understand the mistake I have done.Thank you.
SLLCLAS.CPP
#include<iostream>
#include<conio.h>
class node{
public:
int data;
node *next;
};
class sll{
private:
node *head;
public:
ssl(){
head=NULL;
}
void display();
void insert(int,int);
};
void sll::display(){
if(head==NULL){
cout<<"List is Empty";
}else{
cout<<"\n";
for(node *t=head;t!=NULL;t=t->next){
cout<<t->data<<"->";
}
cout<<"\n";
}
void sll::insert(int position,int data){
node *temp=new node();
temp->data=data;
if(position<0){
cout<<"\nPosition not valid";
}else if(head==NULL || position==1){
temp->next=head;
head=temp;
}else{
node *p,*q;
q=head;
int count=1;
while(count<position && q!=NULL){
count++;
cout<<"\nCount:"<<count;
p=q;
q=q->next;
}
p->next=temp;
temp->next=q;
delete(temp);
}
int main(){
clrscr();
sll list;
int ch,val,pos;
do{
cout<<"\nSINGLY LINKED LIST\n1: Insert\n2: Delete\n3: Display\n Enter your choice:";
cin>>ch;
switch(ch){
case 1:
cout<<"\nEnter the position:";
cin>>pos;
cout<<"\nEnter the value:";
cin>>val;
list.insert(pos,val);
list.display();
break;
case 2:
break;
case 3:
list.display();
break;
default:
cout<<"\nWrong choice";
}
cout<<"\nDo you want to continue(1/0):";
cin>>ch;
}while(ch!=0);
getch();
}
EDIT:
I am running the code on Turbo C++ Version 3.0 on windows 8.1 64bit
using dosbox.
This is a fixed version of the function insert:
void sll::insert(int position, int data) {
node* temp = new node();
temp->data = data;
if (position <= 0) {
cout << "\nPosition not valid";
} else if (head == NULL || position == 1) {
temp->next = head;
head = temp; // ---------------------- problem here
} else {
node* p, *q;
q = head;
int count = 1;
while (count < position && q != NULL) {
count++;
cout << "\nCount:" << count;
p = q;
q = q->next;
}
p->next = temp;
temp->next = q;
}
//delete (temp); //<---------------- problem here
}
You create a node to insert in the list but at the end of the function deleted (with pointer referencing to this memory address), when accessing the memory deleted anything could happen.
The other problem would give you compiler error you are assigning a node variable to a node* variable, with what compiler you are testing.
The are other problems as #include <iostream.h>, iostream is a header from C++ that don't have extension (ex: #include <vector> or #include <iostream>).
The main function it's not standart, changed to int main() if the parameters are not used or int main(int argc, char* argv[]) if they are. You would need to return and integer from main function.
I don't have clrscr(); function defined, probably platform dependent (i am testing with MinGW GCC 4.9.0 with C++11 in Windows).
The statement
delete(temp);
is highly suspicious in the insert function.
Basically temp reference the new node you take care to create and setup. But you delete it before exiting the function. After the first insert, you are manipulating freed memory.
The statement
head=*temp;
make no sense. head is a node*, and you are assigning a node value. If it ever compiles, head is also containing garbage value.
#include <iostream>
using namespace std;
struct node
{
int info;
node *next;
};
class DS
{
private:
node *temp;
node *temp1;
node *head;
int key;
int x;
public:
DS()
{
head=temp=temp1=NULL;
}
void insert()
{
for (int i=0; i<1; i--)
{
cout<<"Enter 0 to stop and 1 to continue:";
cin>>x;
cout<<endl;
if (x==1)
{
if (head==NULL)
{
head=new node;
cout<<"Enter the value in head's Info";
cin>>head->info;
cout<<endl;
head->next=NULL;
}
cout<<"Enter the number after which you want to add node:";
cin>>key;
cout<<endl;
temp=head;
while (temp!=NULL)
{
if (temp->info==key)
{
temp1=new node;
cout<<"Enter value in new node:";
cin>>temp1->info;
cout<<endl;
temp1->next=temp->next;
temp->next=temp1;
}
temp=temp->next;
}
}
else break;
}
}
void Del()
{
temp=head;
if(head==NULL)
return;
cout<<"Enter the number after which you want to delete the node:";
cin>>key;
cout<<endl;
while( temp!=NULL)
{
if (temp->next->info==key)
{
temp1=temp->next;
temp->next=temp->next->next;
delete temp1;
break;
}
temp=temp->next;
}
}
void searching()
{
temp=head;
cout<<"Enter key to found node:";
cin>>key;
cout<<endl;
while (temp!=NULL)
{
if (temp->info==key)
{
cout<<"Node found"<<endl;
break;
}
temp=temp->next;
}
}
void printing()
{
temp=head;
while (temp!=NULL)
{
cout<<endl;
cout<<temp->info<<endl;
temp=temp->next;
}
}
void emptiness()
{
temp=head;
if (temp->next==NULL)
{
cout<<"Empty list";
cout<<endl;
}
else if (temp!=NULL)
cout<<"Not empty";
}
};
int main()
{
DS obj;
obj.insert();
cout<<endl;
obj.Del();
cout<<endl;
obj.searching();
cout<<endl;
obj.printing();
cout<<endl;
obj.emptiness();
return 0;
}