In: Computer Science
Write a c++ member function that attempts to insert a NON DUPLICATE element to a doubly linked list, After the attempted insertion return the SIZE of the doubly linked list whether or not the insertion was successful.
here is a program with function definition and implementation i returned the size as well output the message.
--------------------------------------------------------------------------------------
#include <bits/stdc++.h>
using namespace std;
class dll //class defining doubly linked list
{
public:
int data;
dll *next;
dll *prev;
};
dll *head=NULL; //creating head node
dll *curr=NULL; //creating current node
int size =0; // initially size is 0
int insertifnotpresent(int val) // function for insertion if not
duplicate number
{
dll *temp=head;
for(int i=0;i<size;i++) //checking if val is duplicate or
not
{
if(temp->data==val) // if duplicate size is returned and further
function will not run
{
cout<<"size = "<<size<<", insertion is not
successful.\n";
return size;
}
temp=temp->next;
}
dll *newnode = new dll(); // creating a new node
newnode->data = val; // initializing the node data
newnode->next=NULL;
newnode->prev=NULL;
if(head== NULL) // if newnode is first node
{
curr=head = newnode;
size++;
}
else
{
curr->next =newnode;
newnode->prev = curr;
curr = newnode;
size++;
}
cout<<"size = "<<size<<", insertion is
successful.\n";
return size;
}
int main()
{
int n,val;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>val;
insertifnotpresent(val);
}
return 0;
}
--------------------------------------------------------------------------------------------------
input and corresponding output screen shot
------------------------------
---------------------------------------------------------------------------
feel free to write in comment section if you have any doubt.
do upvote if you like the answer.