Problem 3. (50 pts total) Give a complete template class including functions for
ID: 3912100 • Letter: P
Question
Problem 3. (50 pts total) Give a complete template class including functions for a Self- Organizing List (SOlist). A self organizing list is a list which includes a function organize(x) which removes all elements from the list with value x and adds them back to the front of the list. Your class should include the following: (a) A default constructor to create an empty vector (b) An accessor returning the value of the front of the list. (c) A mutator add which adds to the end of the list. (d) A mutator add which removes from the front of the list. (e) The mutator organize described above.Explanation / Answer
#include<bits/stdc++.h>
using namespace std;
typedef struct node{
int data;
struct node*next;
}node;
class sample{
node * root;
public:
sample(){
root=new node;
root->next=NULL;
}
int get_front(){
if(root->next) cout<<"front element: "<<root->next->data<<" ";
else cout<<"no element in list ";
}
void addnode(){
int d;
cout<<"enter data ";
cin>>d;
node*newnode=new node;
node*temp=root;
newnode->data=d;
newnode->next=NULL;
while(temp->next!=NULL)
temp=temp->next;
temp->next=newnode;
}
void remove_front(){
node*temp=root->next;
if(temp){
root->next=temp->next;
cout<<temp->data<<" is deleted ";
delete(temp);
}
else
cout<<"no front element ";
}
void organize(int x){
node*temp1=root,*temp2=root->next;
node*current;
while(temp1&&temp2){
if(temp2->data==x){
if(temp2==root->next)continue;
else{
temp1->next=temp2->next;
current=temp2;
temp2=temp1->next;
current->next=root->next;
root->next=current;
}
}
else{
temp1=temp1->next;
temp2=temp2->next;}
}
}
void print(){
node*temp=root->next;
while(temp){
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<" ";
}
};
int main(){
int choice,x,more;
sample s;
do{
cout<<"1:add 2:get_front 3:remove front 4:organise 5:print ";
cin>>choice;
switch(choice){
case 1:{
s.addnode();
break;
}
case 2:{
s.get_front();
break;
}
case 3:{
s.remove_front();
break;
}
case 4:{cout<<"enter key ";
cin>>x;
s.organize(x);
break;
}
case 5:{
s.print();
break;
}
}
cout<<"To continue press 1 else press 0 ";
cin>>more;
}while(more==1);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.