Extend the class LinkedListType by adding the following operations: a. Find and
ID: 3681473 • Letter: E
Question
Extend the class LinkedListType by adding the following operations: a. Find and delete the node with the smallest info in the list. (Delete only the first occurrence and traverse the list only once.) b. Find and delete all occurrences of a given info from the list. (Traverse the list only once.) Add these as abstract functions in the class LinkedListType and provide the definitions of these functions in the class UnorderedLinkedList. Also test these functions in Driver program. p.s. Program prints message if we try to remove element from empty list or when we try to remove element that is not in the list.
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
class Node{
public:
int key;
Node * next;
Node(int n){
key=n;
next=NULL;
}
};
class Linkdl{
public:
Node * head;
Linkdl(){
head=NULL;
}
void insert(int n){
Node * nn=new Node(n);
nn->next=head;
head=nn;
}
void deleteall(int n){
if(head==NULL){
}
else{
if(head->key==n){
head=head->next;
}
else{
Node * pre=head;
Node * cur=head->next;
while(cur!=NULL){
if(cur->key==n){
pre=cur->next;
cur->next=NULL;
free(cur);
}
else{
pre=cur;
cur=cur->next;
}
}
}
}
}
void del_small(){
if(head==NULL){
cout<<"No info to delete!"<<endl;
}
else{
node * prev1=NULL;
node * prev2=head;
node * cur=head;
while(cur->next!=NULL){
if(cur->key>cur->next->key){
prev1=cur;
prev2=cur->next;
cur=cur->next;
}
else{
cur=cur->next;
}
}
if(prev1==NULL){
head=head->next;
}
else{
prev1->next=prev2->next;
prev2->next=NULL;
free(prev2);
}
}
}
void print(){
node * cur=head;
while(cur->NULL){
cout<<cur->key<<endl;
}
cout<<endl;
}
};
int main() {
Linkdl l;
l.insert(2);
l.insert(1);
l.insert(2);
l.insert(3);
l.insert(1);
l.insert(3);
l.insert(1);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.