In: Computer Science
C++ Linked Lists
Don’t you love music? Everyone loves a great song playlist! Practice your
understanding of linked lists in C++ by creating list of songs / artist pairs.
Allow your user to add song / artist pairs to the list, remove songs (and
associated artist) from the list and be sure to also write a function to print
the list! Have fun!
`Hey,
Note: In case of any queries, just comment in box I would be very happy to assist all your queries
/*** Below is the complete code and sample output in the end ***/
#include<iostream>
using namespace std;
struct musicNode{
string songName;
string artistName;
musicNode *next;
};
class musicList{
private:
musicNode *head;
public:
musicList(){
head = NULL;
}
void addSong(string sName, string aName){
musicNode *ptr = new musicNode;
ptr->songName = sName;
ptr->artistName = aName;
ptr->next = NULL;
if(head == NULL){
head = ptr;
}
else{
musicNode *current = head;
while(current->next != NULL)
current = current->next;
current->next = ptr;
}
}
void deleteSong(string sName){
musicNode *temp = head;
musicNode *prev = NULL;
if(temp != NULL && temp->songName == sName){
head = head->next;
return;
}
while(temp != NULL && temp->songName != sName){
prev = temp;
temp = temp->next;
}
if(temp == NULL){
cout<<"Song Is not present in the list: "<<endl;
return ;
}
if(temp->next == NULL){
prev->next = NULL;
return ;
}
prev->next = temp->next;
//delete temp;
}
void printList(){
musicNode *current = head;
while(current != NULL){
cout<<current->songName<<":"<<current->artistName<<" -> ";
current = current->next;
}
cout<<endl;
}
};
void displayMenu(){
cout<<"1. Add Song"<<endl;
cout<<"2. Delete Song"<<endl;
cout<<"3. Print music List"<<endl;
cout<<"4. Exit"<<endl;
}
int main(){
musicList mList;
while(true){
displayMenu();
cout<<"Enter your choice"<<endl;
int option;
cin>>option;
cin.ignore(26, '\n');
if(option == 1){
string songName;
string artistName;
cout<<"Enter the song Name"<<endl;
getline(cin,songName);
cout<<"Enter the artist Name"<<endl;
getline(cin,artistName);
mList.addSong(songName, artistName);
}
if(option ==2){
string songName;
cout<<"enter the songName to delete"<<endl;
getline(cin, songName);
mList.deleteSong(songName);
}
if(option ==3){
mList.printList();
}
if(option ==4){
cout<<"Exiting"<<endl;
break;
}
}
}
/*** Output ***/
Kindly revert for any queries
Thanks.