Program in C++ - read all instructions please implement a shopping list that use
ID: 3702588 • Letter: P
Question
Program in C++ - read all instructions
Explanation / Answer
class LinkedList{
public:
LinkedList(){
*myHead = NULL;
*myTail = NULL;
mySize =0;
}
~LinkedList();
int size() const{
return mySize;
}
void addToStart(Node *n){
if(myHead == NULL)
{
myHead = n;
myTail = myHead;
}
else
{
n->next = myHead;
myHead = n;
}
mySize++;
}
void addToEnd(Node *n){
if(myHead == NULL)
{
myHead = n;
myTail = myHead;
}
else
{
myTail->next = n;
myTail = n;
}
mySize++;
}
void printList(){
cout<<"List"<<endl;
cout<<"Item No "<<"Item Name"<<endl;
if (mySize == 0)
{
cout<<"Empty"<<endl;
return;
}
if (myHead->next == NULL)
{
cout<<myHead->itemNo<<" "<<myHead->itemName<<endl;
return;
}
Node *ptr = myHead;
cout<<myHead->itemNo<<" "<<myHead->itemName<<endl;
ptr = myHead->next;
while (ptr->next != NULL)
{
cout<<myHead->itemNo<<" "<<myHead->itemName<<endl;
ptr = ptr->next;
}
cout<<ptr->itemNo<<" "<<ptr->itemName<<endl;
}
bool removeFromStart(){
if(mySize == 0)
cout<<"No items in the list"<<endl;
else{
Node *temp = myHead;
myHead = myHead->next;
free(temp);
mySize--;
}
}
bool removeFromEnd(){
if(mySize == 0)
cout<<"No items in the list"<<endl;
else{
Node *temp = myHead;
Node *rm = myTail;
while(temp->next != myTail)
temp = temp->next;
temp->next = NULL;
myTail = temp;
free(rm);
mySize--;
}
}
void removeNodeFromList(int no) {
if(mySize == 0)
cout<<"No items in the list"<<endl;
else{
Node *prev = myHead;
Node *curr = myHead->next;
if(myHead->itemNo == no){
myHead = myHead->next;
free(prev);
mySize--;
return;
}
while(curr->next != NULL){
if(curr->itemNo == no){
prev->next = curr->next;
curr->next = NULL;
free(curr);
mySize--;
return;
}
else{
prev = curr;
curr = curr->next;
}
}
cout<<"Item not found in the list"<<endl;
}
void removeNodeFromList(string nm) {
if(mySize == 0)
cout<<"No items in the list"<<endl;
else{
Node *prev = myHead;
Node *curr = myHead->next;
if(myHead->itemNo == nm){
myHead = myHead->next;
free(prev);
mySize--;
return;
}
while(curr->next != NULL){
if(curr->itemNo == nm){
prev->next = curr->next;
curr->next = NULL;
free(curr);
mySize--;
return;
}
else{
prev = curr;
curr = curr->next;
}
}
cout<<"Item not found in the list"<<endl;
}
private:
Node *myHead;
Node *myTail;
int mySize;
};
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.