update value c++ (singgle linked listed) - c++

i have a question. how to update value in linked listed. I have a code
void edit() {
node *temp;
temp = awal_ptr;
char goldar[5];
int caridata;
int ketemu=0;
if(awal_ptr != NULL) {
cout<<"\n Input Id Yang Akan Diedit\t: ";
cin>>caridata;
while(temp!=NULL) {
temp->id;
if(caridata==temp->id) {
cout<<">>>------------------------------<<<"<<endl;
cout<<" Nama\t: "<<temp->nama<<endl;
cout<<" Golongan Darah\t: "<<temp->gol<<endl;
cout<<" ------------------------------"<<endl;
ketemu=1;
cout<<"Masukan Golongan Darah Baru: ";
cin>>goldar;
temp->id=caridata;
temp->gol==goldar;
//temp = temp->next;
//temp->id=goldar;
cout<<"Data Berhasil Diupdate"<<endl;
} temp=temp->next;
}
if(ketemu==0) {
cout<<" Data tidak ditemukan";
}
} else cout<<" Belum ada data!";
getch();
}
how to update value goldar (lisked list). when i update goldar. no error but value doesnt change. example i update or edit data with id 112 form A to O. the message succes but the value doesnt change it still A. hope you can help me

temp->gol==goldar;
Try = instead of ==. You are comparing values here, not assigning.

Related

Getting signal sigsegv while sorting a linked list

I am trying to sort a linked list,but i getting this segmentation fault while sorting, tried debuggig but cant find the problem though.
here is the sorting function:
void Asort(struct lol **head_ref)
{
cout<<"Entered in asort function\n";
/// Sorting Asendingly
int temp1; /// to store the temp value
struct lol* temp = *head_ref;
struct lol* next;
while(temp!=NULL)
{
cout<<"Entered in while loop until null\n";
next=temp->next;
cout<<"log: " << next->element;
if(temp->element > next->element && next!=NULL)
{
cout<<"Entered in If condition inside while loop\n";
temp1=next->element;
next->element=temp->element;
temp->element=temp1;
}
temp=temp->next;
}
cout<<"Sorted Asending Successfully\n";
}
Here is calling statement :
Asort(*head)
if(temp->element > next->element && next!=NULL)
There is no point in checking whether next is NULL after you have dereferenced it: if it was NULL, you are already dead.
The order matters; next != NULL && temp->element > next->element would work better.
You have similar bug elsewhere in the program, e.g.
next=temp->next;
cout<<"log: " << next->element; // will crash here if next==NULL

Insertion and deletion in a stack using linked list

The program is about insertion and deletion in a stack using ling lists.The push works fine but there is problem in the deletion the pop() function has some
error. Every time i try to delete something it gives infinite error with underflow. ie. the top pointer is always null.
#include<iostream>
#include<stdlib.h>
#include<process.h>
using namespace std;
struct node
{
int info;
node *next;
}*top,*save,*newptr,*ptr;
node *create_new_node(int);
void push(node*);
void pop();
void display(node*);
int main()
{
top=NULL;
int inf;
char ch='y';
while(ch=='y'||ch=='Y')
{
newptr=new node;
cout<<"\nEnter the info to be added in the beginning of the stack\n";
cin>>inf;
if(newptr==NULL)
cout<<"\nCannot create new node.ABORTING!!\n";
else
{
newptr=create_new_node(inf);
cout<<"\nPress enter to continue\n";
system("pause");
}
push(newptr);
cout<<"\nthe info has been inserted in the stack\n";
cout<<"\nThe stack now is\n";
display(newptr);
cout<<"\ndo you wish to add more elements to the stack.\nIf yes then
press y or else press n\n";
cin>>ch;
if(ch=='n'||ch=='N')
{
cout<<"\ndo you to delete elements from the stack\n";
cout<,"\nIf yes then press d else press n\n";
cin>>ch;
if(ch=='d'||ch=='D')
{
while(ch=='d'||ch=='D')
{
pop();
cout<<"\npress d to delete more elements y to add more
elements and n to exit\n";
cin>>ch;
}
}
}
}
delete(ptr);
delete(newptr);
delete(top);
delete(save);
return 0;
}
node* create_new_node(int n)
{
ptr=new node;
ptr->info=n;
ptr->next=NULL;
return ptr;
}
void push(node *np)
{
if(top==NULL)
top=np;
else
{
save=top;
top=np;
np->next=save;
}
}
void pop()
{
if(top==NULL)
cout<<"underflow";
else
{
ptr=top;
top=top->next;
delete ptr;
}
}
void display(node *np)
{
while(np!=NULL)
{
cout<<np->info<<"->";
np=np->next;
}
}
There are multiple bugs in the shown code.
Your main bug:
while(ch=='d'||ch=='D')
{
pop();
cout<<"\npress d to delete more elements y to add more elements and n to exit\n";
}
At this point, when ch is 'd' or 'D' execution will enter the while loop, of course. A call to pop() is made, which removes the topmost element from the stack, prints a message, and repeats the while loop.
At this point your program will make an important discovery that ch is still either 'd' or 'D'. Nothing has changed its value. A computer program always does exactly what you tell it to do, unfortunately, instead of what you think you want it to do. No matter how hard you look here, you will never find any code here that ever changes the value of ch. It will remain at its current value forever. And so the while loop runs again. And again. And again. Nothing ever changes the value of ch, at this point, so you have an infinite loop.
Additionally, in your main:
newptr=new node;
This pointer's value is later compared to NULL; and if not ... it gets completely overwritten by
newptr=create_new_node(inf);
This accomplishes absolutely nothing, except leaking memory. This code appears to be leftover junk, and should be cleaned up after fixing the faulty while loop logic.

How to use Doubly Linked List with Dynamic Array?

My homework is about making a schedule with doubly-linked list. We can create a dynamic array for keeping days. But every day has to have a doubly-linked list which contains time slots. Vectors and arrays are forbidden from use, instead of linked lists. I have difficulty about functions.
This is my header file:
#ifndef _SCHEDULE_H
#define _SCHEDULE_H
#include <string>
using namespace std;
struct Node
{
string courseName;
int time;
Node *next; //forward direction
Node *prev; //backward direction
Node::Node() {}
Node::Node(const string &cName,const int&time, Node * pRight, Node * pLeft)
: courseName(cName),time(time),next(pRight), prev(pLeft)
{}
};
class Schedule
{
public:
Schedule(); //Constructor
//adding new course depend on time
void addCourse(string courseName, char day, int time,Node *Days[6]);
// delete course depend on time
void deleteCourse(char day, int time,Node *Days[6]);
// display a particular course's time
void displayCourse(string courseName,Node *Days);
//prints schedule
void print(Node *Days);
private:
Node *head; //Head node, start of a linked list based on Day
Node *tail; //Tail node, end of a linked list based on Day
};
#endif
Here's my implementation file:
#include <iostream>
#include "Schedule.h"
using namespace std;
Schedule::Schedule()
{
head=new Node(" ",0,NULL,NULL);
tail = NULL;
}
void Schedule::addCourse(string courseName, char day, int time,Node *Days[6])
{
int i;
if (day=='M')
{i=0;}
else if(day=='T')
{i=1;}
else if(day=='W')
{i=2;}
else if(day=='R')
{i=3;}
else if(day=='F')
{i=4;}
else if(day=='S')
{i=5;}
Node*cur=Days[i]->next=head;
if(Days[i]->next==NULL)
{
Days[i]=new Node;
Days[i]->next->courseName=courseName;
Days[i]->time=time;
Days[i]->next=NULL;
Days[i]->prev=NULL;
cout<<"The course "<<courseName<<" is added on "<<day<<" "<<time<<endl;
}
else if(time<Days[i]->next->time && time!=Days[i]->next->time)
{
Node*newcourse=new Node;
//Days[i]=new Node;
Days[i]->next->courseName=courseName;
Days[i]->next->time=time;
Days[i]->next=head;
Days[i]->prev=NULL;
Days[i]->next=newcourse;
cout<<"The course "<<courseName<<" is added on "<<day<<" "<<time<<endl;
}
else if(time>Days[i]->next->time)
{
while(Days[i]->next!=NULL && Days[i]->next->time<time && Days[i]->next->time!=time)
{
Days[i]->next=Days[i]->next->next;
}
if(Days[i]->next->time==time)
{
cout<<"Time conflict"<<endl;
}
else
{
Node*newcourse=new Node;
Days[i]->next->courseName=courseName;
Days[i]->next->time=time;
Days[i]->next=Days[i]->next->next;
Days[i]->prev=Days[i]->next;
Days[i]->next->next=newcourse;
cout<<"The course "<<courseName<<" is added on "<<day<<" "<<time<<endl;
}
}
}
void Schedule::deleteCourse(char day, int time,Node *Days[6])
{
int d;
if (day=='M')
{d=1;}
else if(day=='T')
{d=1;}
else if(day=='W')
{d=2;}
else if(day=='R')
{d=3;}
else if(day=='F')
{d=4;}
else if(day=='S')
{d=5;}
Node*cur=Days[d]->next=head;
if(Days[d]->next==NULL)
{
cout<<"Schedule is empty for this day"<<endl;
}
else
{
}
}
void Schedule::displayCourse(string courseName,Node *Days)
{
}
void Schedule::print(Node *Days)
{
}
Here is my main:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Schedule.h"
using namespace std;
Node *Days = new Node[6];
void CoutSelection()
{
cout<<endl<<endl;
cout<<"Welcome to Schedule Maker. Please select an option:"<<endl;
cout<<" 1) Load the course schedule from a known file"<<endl;
cout<<" 2) Add a time slot manually"<<endl;
cout<<" 3) Remove a time slot manually"<<endl;
cout<<" 4) Print a particular course's time slot"<<endl;
cout<<" 5) Print all schedule"<<endl;
cout<<" 6) Exit" <<endl;
cout<<endl;
cout<<" Please enter your selection as 1-2-3-4-5-6"<<endl;
cout<<endl;
}
int main()
{
int selection;
CoutSelection();
cin>>selection;
Schedule list;
while (selection!=6)
{
if (selection==1)
{ string fileName;
cout<<"Please enter the filename that you want to load"<<endl;
cin>>fileName;
ifstream input;
input.open(fileName);//open file
if(!input.is_open())//control if correctly open
{
cout<<"Couldn't open input file: "<<fileName<<endl;
}
else
{
string cname,line; //course name and day identifier
char day;
int time; //time
while(!input.eof())
{getline(input, line);
stringstream ss(line);
int num;
ss>>cname>>day>>num;
list.addCourse(cname,day,time,*Days[6]);
}
}
}
else if (selection==2)
{
int timeAdded;
string cnameAdded;
char dayAdded;
cout<<"Please enter course name,day and it's time that you want to add like : coursename dayidentifier time"<<endl;
cout<<"Enter the day as M/T/W/R/F/S. (MONDAY:M, TUESDAY:T, WEDNESDAY:W, THURSDAY:R, FRIDAY:F, SATURDAY:S)"<<endl;
cin>>cnameAdded>>dayAdded>>timeAdded;
list.addCourse(cnameAdded,dayAdded,timeAdded,*Days[6]);
}
else if(selection==3)
{
char dayDeleted;
int timeDeleted;
cout<<"Please enter the day and time that you want to delete like : dayidentifider time"<<endl;
cout<<"Enter the day as M/T/W/R/F/S. (MONDAY:M, TUESDAY:T, WEDNESDAY:W, THURSDAY:R, FRIDAY:F, SATURDAY:S)"<<endl;
cin>>dayDeleted>>timeDeleted;
list.deleteCourse(dayDeleted,timeDeleted,*Days[6]);
}
else if(selection==4)
{
string coursedisplayed;
cout<<"Please enter course name that you want to display"<<endl;
cin>>coursedisplayed;
list.displayCourse(coursedisplayed,*Days);
}
else if(selection==5)
{
list.print(*Days);
}
CoutSelection();
cin>>selection;
}
return 0;
}
What is wrong with my code? If I handle one of the functions, I'm sure I can do other functions.
Errors :
error C2664: 'Schedule::addCourse' : cannot convert parameter 4 from 'Node' to 'Node *[]'
IntelliSense: no operator "*" matches these operands
operand types are: * Node
Aside from all the problems presented by #WhozCraig, which I think you should tackle for your own good. Your compiler is talking to you, and it is telling you that your addCourse method receives a pointer to a Node Array.
But in your main you called it with the following list.addCourse(cname,day,time,*Days[6]);. By doing *Days[6] you are telling the method you want to send what is pointed by Days[6]. Thus your compiler is receiving a Node object and not a pointer to a node array.
Try it with the following list.addCourse(cname,day,time,Days);, this will send the pointer to the first element in days.
One pointer to keep in mind, which you'll teacher will likely notice:
You have memory leaks, which is another VERY important subject.

user defined variables on the heap getting destroyed in while loop

I an odd problem that i cant understand if someone could point me in the right direction it would be greatly appreciated.I create my own linked list variables on the heap but when i go to add another variable to it they all get destroyed and i dont know why.
in my main i set up my variables like this
main.cpp
Book* temp;
temp = bookSetUp();
this goes to a different cpp called functions which sets up the objects like this:
functions.cpp
Book* bookSetUp()
{
//The items that populate the list
Book* a= new Book("A Tale of Two Cities", "Charles Dickens", "1", true);
Book* b= new Book("Lord of the rings", "J.R.R Tolkein", "2", true);
Book* c= new Book("Le Petit Prince", "Antoine de Saint-Exupéry", "3", true);
Book* d= new Book("And Then There Were None", "Agatha Christie", "4", true);
Book* e= new Book("Dream of the Red Chamber","Cao Xueqin","5", true);
Book* f= new Book("The Hobbit","J.R.R Tolkein","6", true);
//sets up the pointers between books
a->setPrev(NULL);
a->setNext(b);
b->setPrev(a);
b->setNext(c);
c->setPrev(b);
c->setNext(d);
d->setPrev(c);
d->setNext(e);
e->setPrev(d);
e->setNext(f);
f->setPrev(e);
f->setNext(NULL);
//sets up a temp pointer to a
Book* temp = a;
//returns the temp pointer to a
return temp;
}
this works perfectly but later on when i go to add to the list again in the main using:
main.cpp
else if(checkRegUser(username, password, regUserList) == true)
{
int choice = 99;
cout << "Welcome Registered user: "<< username << endl;
while(choice != 0)
{
//this is so the print will start everytime as if you run it once print will be at NULL thereafter
Book* print = temp;
choice = options();
if(choice == 1)
{
while(print!=NULL)
{
cout<<"Name: "<<print->getName()<<endl<<"Author: "<<print->getAuthor()<<endl<<"ISBN: "<<print->getISBN()<<endl<<"Availability: "<<print->getAvail()<<endl;
cout<<endl;
print = print->getNext();
}
print = temp;
}
if(choice == 2)
{
search(temp);
}
if(choice == 3)
{
takeOut(temp);
}
if(choice == 4)
{
returnBack(temp);
}
if(choice == 5)
{
append(temp);
}
if(choice == 6)
{
cout<<"Sorry you have the privilege needed to use this function."<<endl;
}
if(choice == 7)
{
choice = 0;
}
}
}
My user defined variables get destroyed. I debugged and they just disappeared i am not sure why!
Just in-case its needed here is my add() function because I feel It could be me missing something small or just making a disastrous mistake. My add function is in the functions.cpp and I know all the links are working as I have everything else running apart from this
functions.cpp
Book* append(Book* tempParam)
{
string title;
string author;
string isbn;
bool avail;
cout<<"What is the book called?"<<endl;
cin.clear();
cin.ignore();
getline(cin, title);
cout<<"Who is the author?"<<endl;
cin.clear();
cin.ignore();
getline(cin, author);
cout<<"What is the ISBN to be?"<<endl;
cin>>isbn;
Book* temp = new Book(title, author, isbn, true);
Book* list = tempParam;int count;
while(list!=NULL)
{
if(list->getNext()==NULL&&list->getName()!=title)
{
list->setNext(temp);
temp->setNext(NULL);
temp->setPrev(list);
cout<<"Your book has been added"<<endl;
cout<<temp->getName()<<temp->getAuthor()<<endl;
}
list = list->getNext();
}
tempParam = list;
return tempParam;
}
My user defined classes are working perfectly its just when I go to add that my list gets destroyed any ideas??
*I think the error is found in this section of the code:
list->setNext(temp);
You are "losing" the books because you didn't save them before you change list->next.*
The answer is incorrect because the conditional statement makes sure that it is the last element of the list. Sorry!

Error in a Link List

I wrote the following code for a Link list to create a Book its serial no. and search it. I am using linked list in it.
When I add my first entry , it is added successfully, but when I add second entry it shows segmentation fault. I am not able to figure out why. Please help.Thanks in advance.Code:
#include<iostream>
#include<string>
#include<fstream>
#include<cstdlib>
using namespace std;
struct book
{
int accno;
string name;
book* next;
};
int main()
{
bool flag=false;
int x,m;
string s;
book* front=NULL;
book* n;
do
{
cout<<"\nPlease select the following:\n1.Create and append\n2.Search\n3.Exit";
cin>>m;
switch(m)
{
case 1:
n=new book();
cout<<"\nEnter the book name: ";
cin>>s;
cout<<"\nEnter the acc no.: ";
cin>>x;
if(front==NULL)
{
front=n;
}
else
{ n=front;
while(n->next!=NULL)
{
n=n->next;
}
n=n->next;
}
n->accno=x;
n->name=s;
break;
case 2:
cout<<"Enter the roll no.";
int y;
cin>>y;
if(front==NULL){cout<<"Doesnot exist\n"; break;
}
else
{
n=front;
while(n->accno!=y && n->next!=NULL)
{
n->next=n;
}
cout<<"Book name is:"<<n->name;
cout<<"\nAccno is: "<<n->accno;
}
break;
case 3: flag=true;
break;
}
}
while(flag==false);
return 0;
}
Here
while(n->next!=NULL)
{
n=n->next;
}
n=n->next;
you iterate through the linked list to find the last element, then step past it. After this, n will be null.
What you are missing is creating a new element and appending it to the end of the list.
And here
n->accno=x;
n->name=s;
you must also assign n->next = null, otherwise your list won't be properly terminated.
Also, when searching for a book, here
while(n->accno!=y && n->next!=NULL)
{
n->next=n;
}
cout<<"Book name is:"<<n->name;
cout<<"\nAccno is: "<<n->accno;
after exiting the loop, either you found the book or n is null. You must check which is the case before trying to dereference n, otherwise you will again get a segfault if the book you are looking for is not in the list.
Learn to write a linked list (so if this is a homework targeted at learning them, it's valid, but it is not tagged as such), but never ever do it in practice. There is a standard library and there is boost and they have all data structures you'll need unless you do something really special.
You have C++, so don't write C-style code. book should have a constructor that should initialize it's members. The list head should probably be encapsulated in the class too and manipulated using it's methods.
You never set n->next, so don't be surprised it never contains anything meaningful.
You re-use n in the loop forgetting the object you constructed (memory leak).
Than you get the NULL at the end of the list instead of the object you constructed.
here lies your problem:
....
else
{
n=front;
while(n->next!=NULL) //access to next will cause seg fault!!!
{
n=n->next;
}
n=n->next; // step once more, now we have NULL on second add...
}
also, where is n->next being assigned? I don't see it anywhere?
What are you doing here?
case 1:
n=new book();
cout<<"\nEnter the book name: ";
cin>>s;
cout<<"\nEnter the acc no.: ";
cin>>x;
if(front==NULL)
{
front=n;
}
else
{
n=front;
}
while(n->next!=NULL)
{
n=n->next;
}
n=n->next;
}
n->accno=x;
n->name=s;
break;
You have created new book and assigned it to n, in first case its ok becasue your are directly assigning it to front. But in other case you should iterate list using someother variable (temp), when your write n = front, your have already lost your new book object pointer. Hope you got your answer.
This is a buggy code:
You need null the "next" field when you add a new node:
case 1:
new book();
n->next = NULL;
...
You have the memory leakage