I'm a beginner in coding. I am woring on a mini project to write a car parking system from my college. I used doubly-linked list to insert, search and delete to add, search and remove cars in the system .In this program, everything works fine untill i compile the program to remove a Car.Whenever i enter the car number to remove it from parking the error occurs and the carparking.exe suddenly stops.
This is my program:
#include <iostream>
using namespace std;
struct node
{
int no;
int charge,entry_time,exit_time;
char name[20];
node *prev, *next;
};
class Car
{
private:
node *head;
char ch[20];
public:
Car()
{
head= NULL;
}
void input()
{
cout<<"\nWelcome to Car Parking system\n"<<endl;
cout<<"\n Press 1: To Park a Car"<<endl;
cout<<"\n Press 2: To Search a Car"<<endl;
cout<<"\n Press 3: To Remove of Car"<<endl;
cout<<"\n Press 4: To display the Parking records"<<endl;
cout<<"\n Press 5: Exit the program"<<endl;
return;
}
void add_car()
{
node *newer= new node;
system("cls");
cout<<"Enter the Car number: "<<endl;
cin>>newer->no;
fflush(stdin);
cout<<"Enter the name of driver: "<<endl;
cin.getline(newer->name,20);
fflush(stdin);
cout<<"Enter the entry time of car"<<endl;
cin>>newer->entry_time;
fflush(stdin);
cout<<"Enter the exit time of car"<<endl;
cin>>newer->exit_time;
fflush(stdin);
newer->charge=(newer->exit_time-newer->entry_time)*300;
newer->next =head;
newer->prev =NULL;
if(head!=NULL)
{
head->prev = newer;
}
head= newer;
cout<<"\nThe car is parked successfully"<<endl;
if(head==NULL)
{
cout<<"\n No Car is parked: "<<endl;
}
}
void del_car()
{
if(head==NULL)
{
cout<<"\n No Car is parked "<<endl;
}
else
{
int value;
cout<<"\nEnter the Car number to move"<<endl;
cin>>value;
node *temp=head;
bool flag=false;
if(temp->no== value)
{
head=temp->next;
head->prev=NULL;
flag= true;
delete temp;
if(flag==true)
{
cout<<"\nThe Parking charge is Rs "<<temp->charge<<" only"<<endl;
cout<<"The car is moved out of parking zone"<<endl;
}
}
else
{
while (temp!=NULL)
{
if(temp->no==value)
{
node *p,*q;
if(temp->next==NULL)
{
p=temp->prev;
p->next=NULL;
flag=true;
delete temp;
}
else
{
p=temp->prev;
q=temp->next;
p->next=q;
q->prev=p;
flag=true;
delete temp;
}
}
temp=temp->next;
}
if(flag==false)
{
cout<<"\n\t The car number is not found"<<endl;
}
}
}
}
void display()
{
if(head==NULL)
{
cout<<"No Car is parked"<<endl;
}
else
{
node *temp= head;
while(temp!= NULL)
{
cout<<"\n------------------------------Information----------------------------------------"<<endl;
cout<<"\n\tThe name of the driver is:"<<temp->name<<endl;
cout<<"\n\tThe Car number is: "<<temp->no<<endl;
cout<<"\n\tThe entry time of the car is: "<<temp->entry_time<<endl;
cout<<"\n\tThe exit time of the car is: "<<temp->exit_time<<endl;
temp =temp->next;
}
}
}
void search()
{
if(head==NULL)
{
cout<<"No Car is parked"<<endl;
}
else
{
int value;
cout<<"\nEnter the car number to search"<<endl;
cin>>value;
node *temp=head;
bool flag=false;
if(temp->no=value)
{
cout<<"\n\t----Information of the Car-----"<<endl;
cout<<"\nThe name of the driver is: "<<temp->name<<endl;
cout<<"\nThe Car number is: "<<temp->no<<endl;
cout<<"\nThe entry time is: "<<temp->entry_time<<endl;
cout<<"\nThe Car is still Parked "<<endl;
cout<<"\nThe Parking charge is still pending "<<endl;
return;
}
temp= temp->next;
}
}
};
int main()
{
int n;
string ch;
Car c1;
x2:
c1.input();
cout<<"\n\t----Enter your choice----"<<endl;
cin>>n;
if(n==1)
{
x1:
c1.add_car();
cout<<"\nDo you want to go to Main Menu: Press(y or n)"<<endl;
cin>>ch;
fflush(stdin);
if(ch=="Y" || ch=="y")
{
goto x2;
}
else
{
exit(1);
}
}
else if(n==2)
{
c1.search();
cout<<"\nDo you want to go to Main Menu: Press(y or n)"<<endl;
cin>>ch;
if(ch=="Y"||ch=="y")
{
goto x2;
}
else
{
exit(1);
}
}
else if(n==3)
{
c1.del_car();
cout<<"\nDo you want to go to Main Menu: Press(y or n)"<<endl;
cin>>ch;
if(ch=="Y"||ch=="y")
{
goto x2;
}
else
{
exit(1);
}
}
else if(n==4)
{
c1.display();
cout<<"\nDo you want to go to Main Menu: Press(y or n)"<<endl;
cin>>ch;
if(ch=="Y"||ch=="y")
{
goto x2;
}
else
{
exit(1);
}
}
else if(n==5)
{
exit(1);
}
else
{
cout<<"\n\tChoose correct number"<<endl;
goto x2;
}
return 0;
}
In the function del_car()
if(temp->no== value)
{
head=temp->next;
head->prev=NULL;
}
If there is only car parked, then only head is valid and head->next and head->prev will be NULL. Now,
head = temp->next; // head becomes NULL here
head->prev = NULL; //you are dereferencing a NULL pointer and hence the seg. fault
Just setting head = NULL should do in this condition.
Also, if there are more cars parked, the condition is while(temp!=NULL), but if the car is found, then you have to break the loop so that temp won't be incremented unnecessarily. Add a break; after flag=true;.
Related
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
this code uses linked list to make employees records and there is many functions the user can make all of the function except when i use the deleterecord function if there is a record and I type in the id it shows me a segmentation fault
output here
this is the deleterecord function
int deleterecord(){
int id;
Node *temp = new Node();
temp = head;
cout<<"insert employee id: ";
cin>>id;
while(temp!=NULL){
if(temp->next->id==id){
temp->next=temp->next->next;
cout<<"record has been deleted";
return 0;
}
else{
temp=temp->next;
}
}
return -1;
}
and this is the whole code using classes and linked list
#include <iostream>
using namespace std;
class Node{
public:
string name,firstDay,address;
int id,phone,Whours,salary;
Node *next;
};
class linkedlist{
Node* head;
public:
linkedlist(){head=NULL;}
Node* newList(){
Node *head = new Node();
return head;
}
void insertrecord(int id){
string name,firstDay,address;
int phone,Whours,salary;
Node* newNode = new Node();
Node *temp = new Node();
temp = head;
while(temp!=NULL){
if(temp->id==id){
cout<<"record already exist";
return;
}
else{
temp=temp->next;
}
}
temp = head;
cout<<"insert employee name: ";
cin>>name;
cout<<"insert employee first day of work: ";
cin>>firstDay;
cout<<"insert employee phone number: ";
cin>>phone;
cout<<"insert employee address: ";
cin>>address;
cout<<"insert employee salary: ";
cin>>salary;
newNode->name=name;
newNode->id=id;
newNode->firstDay=firstDay;
newNode->phone=phone;
newNode->address=address;
newNode->Whours=32;
newNode->salary=salary;
if(head==NULL||head->id>=id){
newNode->next=head;
head=newNode;
return;
}
while(temp->next!=NULL&&temp->next->id < id)
{
temp=temp->next;
}
newNode->next=temp->next;
temp->next= newNode;
}
int deleterecord(){
int id;
Node *temp = new Node();
temp = head;
cout<<"insert employee id: ";
cin>>id;
while(temp!=NULL){
if(temp->next->id==id){
temp->next=temp->next->next;
cout<<"record has been deleted";
return 0;
}
else{
temp=temp->next;
}
}
return -1;
}
void updaterecord(){
int n,input,id;
string Input;
cout<<"insert employee id: ";
cin>>id;
Node *temp = new Node();
temp = head;
while(temp!=NULL){
if(temp->id==id){
do{
cout<<"what do you like to update:\n1.name\n2.First day\n3.phone number\n4.address\n5.working hours\n6.salary\nenter -1 to cancel\n";
cin>>n;
if(n==1){
cout<<"enter the new name: ";
cin>>Input;
temp->name=Input;
}
else if(n==2){
cout<<"enter the new First day: ";
cin>>Input;
temp->firstDay=Input;
}
else if(n==3){
cout<<"enter the new phone number: ";
cin>>input;
temp->phone=input;
}
else if(n==4){
cout<<"enter the new address: ";
cin>>Input;
temp->address=Input;
}
else if(n==5||n==6){
updatesalary(id);
}
else if(n==-1){
return;
}
}while(n!=-1);
}
else{
temp=temp->next;
}
}
cout<<"record does not exist";
}
void ShowRecord(){
Node *temp = new Node();
temp = head;
if(temp==NULL){
cout<<"there is no records";
return;
}
while(temp!=NULL){
cout<<"name: "<<temp->name<<"\n"
<<"ID: "<<temp->id<<"\n"
<<"First day of work: "<<temp->firstDay<<"\n"
<<"Phone number: "<<temp->phone<<"\n"
<<"Address: "<<temp->address<<"\n"
<<"Working hours: "<<temp->Whours<<"\n"
<<"Salary: "<<temp->salary<<"\n";
temp=temp->next;
}
}
void searchrecord(int id){
Node *temp = new Node();
temp = head;
if(temp==NULL){
cout<<"there is no records";
return;
}
while(temp!=NULL){
if(temp->id==id){
cout<<"name: "<<temp->name<<"\n"
<<"ID: "<<temp->id<<"\n"
<<"First day of work: "<<temp->firstDay<<"\n"
<<"Phone number: "<<temp->phone<<"\n"
<<"Address: "<<temp->address<<"\n"
<<"Working hours: "<<temp->Whours<<"\n"
<<"Salary: "<<temp->salary<<"\n";
return;
}
else{
temp=temp->next;
}
}
}
void updatesalary(int id){
int twopercent,extraS,ew;
Node *temp = new Node();
temp = head;
while(temp!=NULL){
if(temp->id==id){
cout<<"enter the extra working hours:";
cin>>ew;
twopercent=temp->salary*0.02;
extraS = twopercent*ew;
temp->salary=temp->salary+extraS;
cout<<"salary has been updated\n";
return;
}
}
cout<<"record does not exist";
}
};
int main() {
linkedlist records;
int n,id;
while(n!=7){
cout<<"\nplease choose the operation you like to make:\n1.Insert employee record\n2.Delete employee record\n3.update employee record\n4.show employee record\n5.search employee record\n6.update employee salary\n7.Exit\n";
cin>>n;
if(n==1){
cout<<"insert employee id: ";
cin>>id;
records.insertrecord(id);
}
else if(n==2){
int result;
result=records.deleterecord();
if(result==0){
cout<<"record has been deleted";
}
else{
cout<<"record does not exist";
}
}
else if(n==3){
records.updaterecord();
}
else if(n==4){
records.ShowRecord();
}
else if(n==5){
cout<<"insert employee id: ";
cin>>id;
records.searchrecord(id);
}
else if(n==6){
cout<<"insert employee id: ";
cin>>id;
records.updatesalary(id);
}
}
return 0;
}
You can make a node and store the node to be deleted in it and than use delete function to delete the node as follows,
int deleterecord(){
int id;
Node *temp = new Node();
temp = head;
Node *a;
cout<<"insert employee id: ";
cin>>id;
if(temp->id==id)
{
a=temp;
temp = temp->next;
delete(a);
return 0;
}
else
{
while(temp!=NULL){
if(temp->next->id==id){
a = temp->next;
temp->next=temp->next->next;
delete(a);
return 0;
break;
}
else{
temp=temp->next;
}
}
}
return -1;
}
Secondly, you are not checking for the condition if we want to delete 1 node that is a head node. Therefore, the "if" statement needs to be added to your code.
The code I have suggested above clearly solves the problem.
I have made a program in c++ to delete a node in a singly linked list but it is not working as predicted. I am attaching pictures of the output for better clarity that whats misbehaving.
code:
int del_node(int val_del) //this section is producing error
{
node* temp_del=head;
if(head==nullptr)
{
cout<<"no element to delete.!";
exit(0);
}
else
{
while(temp_del->next!=nullptr)
{
if(temp_del->next->data==val_del)
{
temp_del->next=temp_del->next->next;
delete temp_del->next->next;
}
temp_del=temp_del->next;
}
}
return 0;
}
This a function of a class.
Here is the complete code if it helps:
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class linked_list
{
node *head,*tail;
public:
linked_list()
{
head=nullptr;
tail=nullptr;
}
int create_last(int val_last)
{
node *temp=new node; if(!temp){cout<<"memory not allocated"; exit(1);}
temp->data=val_last;
temp->next=nullptr;
if(head==nullptr)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
tail=temp;
}
return 0;
}
int create_beg(int val_beg)
{
node *temp_head=nullptr;
node *temp=new node; if(!temp){cout<<"memory not allocated"; exit(1);}
temp->data=val_beg;
temp->next=nullptr;
if(head==nullptr)
{
head=temp;
tail=temp;
}
else
{
temp_head=head;
head=temp;
temp->next=temp_head;
}
return 0;
}
int del_node(int val_del) //this section is producing error
{
node* temp_del=head;
if(head==nullptr)
{
cout<<"no element to delete.!";
exit(0);
}
else
{
while(temp_del->next!=nullptr)
{
if(temp_del->next->data==val_del)
{
temp_del->next=temp_del->next->next;
delete temp_del->next->next;
}
temp_del=temp_del->next;
}
}
return 0;
}
int show()
{
node* temp_show=head;
while(temp_show!=nullptr)
{
cout<<temp_show->data<<"\n";
temp_show=temp_show->next;
}
return 0;
}
}info;
int main()
{
int choice,ele; char cont;
rep:
cout<<"1. Insert node at the end\n";
cout<<"2. Insert node at beg\n";
cout<<"3. Delete node\n";
cout<<"4. Show nodes\n";
cout<<"5. Exit\n";
cout<<"enter your choice: ";
cin>>choice;
switch(choice)
{
case 1: cout<<"Enter element: ";
cin>>ele;
info.create_last(ele);
break;
case 2: cout<<"Enter element: ";
cin>>ele;
info.create_beg(ele);
break;
case 3: cout<<"Enter element: ";
cin>>ele;
info.del_node(ele);
break;
case 4: info.show();
break;
case 5: exit(0);
break;
default: cout<<"Wrong choice, Bye.!!";
exit(0);
}
cout<<"Do you want to continue(y/n): ";
cin>>cont;
if(cont=='y'||cont=='Y')
{
goto rep;
}
else
{
cout<<"thank you";
exit(0);
}
return 0;
}
int del_node(int val_del) {
node* temp_del = head;
if(head == nullptr) {
cout<<"no element to delete.!";
exit(0);
} else if(head->data == val_del) {
// If head is to be deleted
head = head->next;
} else {
while(temp_del->next != nullptr) {
if(temp_del->next->data == val_del) {
temp_del->next=temp_del->next->next;
// delete temp_del->next->next; This is wrong deletion
}
temp_del = temp_del->next;
}
}
// delete the node if one found else not
if (temp_del != nullptr)
delete temp_del;
return 0; // This should return true or false, do check what you want as return type
}
The del_node function has two problems:
1) It can't delete the node when the list has exactly 1 element
2) It deletes the wrong element
So let's start with number 1 and look at the code:
if(head==nullptr)
{
cout<<"no element to delete.!";
exit(0);
}
else
{
while(temp_del->next!=nullptr)
Assume that the list contains exactly one element. That means:
a) head is not NULL
b) head->next and therefore also temp_del->next is NULL
so while(temp_del->next!=nullptr) will result in false, i.e. the loop will no be executed. The overall result is that the code does nothing.
Now for number 2. The code is:
if(temp_del->next->data==val_del)
{
temp_del->next=temp_del->next->next; // You want to delete temp_del->next
// but here you change it
delete temp_del->next->next; // so here you delete the wrong node
// there is also an extra ->next
}
You need a temp variable to hold a pointer to the node you want to delete.
You probably want the code to be:
int del_node(int val_del)
{
// Delete elements in the front
while (head!=nullptr && head->data==val_del)
{
node* node_to_delete = head;
head = head->next;
delete node_to_delete;
// return 0; Uncomment if you only want one delete per function call
}
if(head==nullptr) return 0;
// Delete elements not in the front
node* temp_del=head;
while(temp_del->next!=nullptr)
{
if (temp_del->next->data==val_del)
{
node* node_to_delete = temp_del->next;
temp_del->next = temp_del->next->next;
delete node_to_delete;
// return 0; Uncomment if you only want one delete per function call
}
temp_del=temp_del->next;
}
return 0;
}
When I am running this program having error in reading file compiler show error of access violation please help me out in this matter I have tried << and >> operators for writing and reading but I am using next pointer due to which I cannot use these operator
#include<iostream>
#include<conio.h>
#include<string>
#include<fstream>
using namespace std;
class employee
{ private:
int id;
static int count;
public:
string name;
employee *next;
employee()
{ cout<<"enter name:";
cin>>name;
count++;
id=count;
next=NULL;
}
employee(int x)
{}
void setcount(int x)
{count=x;}
void show()
{cout<<"Name: "<<name<<endl;
cout<<"id: "<<id<<endl;
}
void setname(string s)
{name=s;}
string getname()
{return name;}
int getid()
{return id;}
};
int employee::count=0;
class db
{ employee *list;
public:
db ()
{ list=NULL; }
void hire()
{employee *e=new employee;
employee *temp=list;
if(list==NULL)
{list=e;}
else{
while(temp->next!=NULL)
{ temp=temp->next; }
temp->next=e;
}//else end
cout<<"hired..."<<endl;
}
void displayall()
{ if(list==NULL)
cout<<"NO record..";
else
{ employee *temp=list;
while(temp!=NULL)
{temp->show();
temp=temp->next; }
}//else end
}
void remove()
{ int id;
int found=0;
cout<<"Enter id to be removed...";
cin>>id;
if(list==NULL)
cout<<"no record..";
else
{ employee *temp=list;
employee *pre=list;
while(temp!=NULL)
{ if( temp->getid()==id)
{ found=1;
employee *e=temp;
e->show();
if(temp==list) //first item to b removed
list=list->next;
else
pre->next=temp->next;
delete e; cout<<"record deleted"<<endl;
break;
}
pre=temp;
temp=temp->next;
}//while end
if(found==0)
cout<<"record not found.."<<endl;
}//else end
}
void searchbyname()
{ string name;
int found=0;
cout<<"enter name..";
cin>>name;
if(list==NULL)
cout<<"no record..";
else
{ employee *temp=list;
while(temp!=NULL)
{ if( temp->getname()==name)
{ found=1;
temp->show();}
temp=temp->next;
}//while end
if(found==0)
cout<<"record not found.."<<endl;
}//else end
}
void save()
{ ofstream out;
out.open("eb",ios::out | ios::binary);
if(!out)
cout<<"cannot save..";
else
{ employee *temp=list;
while(temp!=NULL)
{ out.write((char*) temp,sizeof(employee));
temp=temp->next;
}
out.close();
}
}
void retrieve()
{ ifstream in;
in.open("eb",ios::in | ios::binary);
if(!in)
cout<<"cannot retrieve..";
else
{ employee *temp=NULL;
employee e(0);
while(1)
{ in.read((char*) &e,sizeof(employee));
employee *p=new employee(e); //dynamically creating an employee that will have the same value as 'e' and saving its address in p. Every node in link list has different location so p will be different. &e is always same. So actually read node from file in e than create a node dynamically with same contents and address will be save in p.
if(list==NULL)
{list=p;
temp=list;
p->show();}
else{
temp->next=p;
temp=temp->next;
e.show();
if(e.next==NULL)
{ e.setcount(e.getid()); break;}
}
}
in.close();
}
}
};
void main()
{
db obj;
try{ obj.retrieve();
int op;
while(1)
{ cout<<endl<<"Enter 1 to hire ,2 for remove ,3 for displayall, 4 for search by name.. 5 for exit";
cin>>op;
switch(op)
{case 1:
obj.hire(); break;
case 2:
obj.remove(); break;
case 3:
obj.displayall(); break;
case 4:
obj.searchbyname(); break;
}
if(op==5)
break;
}
obj.save();
}
catch(...)
{cout<<"error..";}
getch();
}
You can not read your class data from the file using this code: in.read((char*) &e,sizeof(employee)); Your class contains std::string and pointers, they will be initialized by the values, that point nowhere. Any attempt to use them is an undefined behavior, leading to the AV in your case.
I have a C++ Code that just manipulates basic linked list - add a new node, delete a node and view the list
//UNIX Environment
#include <iostream>
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
#define clear() printf("\033[H\033[J")
using namespace std;
struct node
{
int val;
node *next;
};
struct node* head = NULL;
void add_node(struct node *hea)
{
char f;
int val;
cout<<"Enter value : ";
cin>>val;
if(head==NULL)
{
head = new(struct node);
head->val = val;
head->next = NULL;
}
else
{
node *traverser = hea;
node *traverser_prev = NULL;
while(traverser!=NULL)
{
traverser_prev = traverser;
traverser=traverser->next;
}
traverser = new(struct node);
traverser->val = val;
traverser->next = NULL;
traverser_prev->next=traverser;
}
cout<<"\nEnter Y to return : ";
cin>>f;
while(f!='Y')
{
cout<<"Wrong entry.Enter again : ";
cin>>f;
}
return;
}
void view_list(struct node *hea)
{
char f;
node *traverser = hea;
while(traverser!=NULL)
{
cout<<traverser->val<<" ";
traverser=traverser->next;
}
cout<<"\nEnter Y to return : ";
cin>>f;
while(f!='Y')
{
cout<<"Wrong entry.Enter again : ";
cin>>f;
}
return;
}
void delete_node(node *hea)
{
char f;
int del_value;
cout<<"Enter value to be deleted :";
cin>>del_value;
node *traverser = hea;
cout<<"OK1\n";
node* traverser_prev = NULL;
cout<<"OK2\n";
while(traverser!=NULL)
{
if(traverser->val==del_value)
{
if(traverser==hea)
{
hea=traverser->next;
cout<<"Here cond1\n";
delete traverser;
}
else
{
traverser_prev->next = traverser->next;
cout<<"Here cond2\n";
}
}
else
{
traverser_prev = traverser;
traverser = traverser->next;
cout<<"Here cond3\n";
}
}
cout<<"\nEnter Y to return : ";
cin>>f;
while(f!='Y')
{
cout<<"Wrong entry.Enter again : ";
cin>>f;
}
return;
}
int main(int argc, char* argv[])
{
while(1)
{
clear();
int choice;
cout<<"POINTER BASICS\n";
cout<<"1. Add new element\n";
cout<<"2. View elements\n";
cout<<"3. Delete element\n";
cout<<"4. Exit\n";
cout<<"Enter choice: ";
cin>>choice;
switch(choice)
{
case 1: add_node(head);
break;
case 2: view_list(head);
break;
case 3: delete_node(head);
break;
default:break;
}
if(choice==4)
break;
}
}
However, whenever I try to delete node, it throws me a segmentation fault error with core dumped. What is the reason for the error?
One problem is that in the delete_node function you pass the list head by value, which means that the pointer is copied and inside the function you only modify the copy.
There are two solutions: Either don't use the argument at all and only use the global variable, or pass the argument by reference:
void delete_node(node*& hea)
Is it possible that when you are executing the line
traverser_prev->next = traverser->next;
traverser_prev == NULL?