SlideShare a Scribd company logo
1 of 11
Download to read offline
Homework 05 - Linked Lists (C++)
(1) Implement the concepts of a union, and difference as defined noted in Chapter 1 questions 6,
and 8 using a linked list. You should not use arrays, dynamic arrays or the STL vector or STL
list classes.
You will be linking a series of nodes together to implement a single linked list class. Define a
Node as a struct that holds a character (like they did in the book) and a pointer to another Node:
struct Node {
char data;
Node* next;
};
Then define a LinkedList class which has (at a minimum) these member functions:
LinkedList();
~LinkedList();
bool insertAtFront();
bool insertBeforePosition(int index);
bool insertAtBack();
bool deleteAtFront();
bool deleteBeforePosition(int index);
bool deleteAtBack();
Implement each of these functions to provide the correct functionality. These functions return
true if successful in inserting or deleting, otherwise they return false (indicating the operation
was not successful).
Finally, create an overloaded + operator to handle the Union of two linked lists and an
overloaded - operator to handle the Difference of two linked lists.
Because we are dealing with pointers you should have both a LinkedList Constructor and
Destructor. Remember that you do not directly call a Constructor or Destructor Function. The
Destructor is automatically called when the variable loses scope or the program ends.
Remember, that we are dealing with not just one dynamically allocated Node (with the new
operator), but many, so you will have to start at the head of the list and go until the Node points
to nullptr. Then keep deleting the previous Node pointer until there are no Nodes left to delete.
(2) To verify your set class, write a main function that takes two lines of characters from the
input file input.txt and store each line of characters into two separate linked lists. Then using
these two lists, perform the Union and set Difference of the characters from the file, and print the
results to the console.
(3) Please also complete an asymptotic (Big O) analysis of your insertAtFront() and
insertAtBack() member functions. Place this in a file called analysis.txt.
Solution
Here is the complete code for your question. Please do rate the aswer if you are happy with
program. Please read comments in the program. Also pay special attention to comments in + and
- operators. You WILL NEED to comment out if condition in + if you want all elements in both
lists irrespective of if they duplicates or no. For now implemented to have true behaviour of no
duplicates in union.
check the functions by creating some lists and playing around different fucntions like its done in
main and commented out.
As far as complexity:
for insertAtFront() its O(1) since it does not depend on the size of the list. It just replaces the start
of the list. Hence it is O(1) and independent of the size of list.
for insertAtBack(), its O(n) since it depends on the number of elements in the list. It should
traverse till end of list and then insert. So it depends on list size and hence O(n).
=======================================
#include
#include
using namespace std;
struct Node
{
char data;
Node *next;
};
class LinkedList
{
Node *start;
public:
LinkedList()
{
//initialize to NULL since no nodes are in the list
start=NULL;
}
//Destructor to free all nodes that were in the list
~LinkedList()
{
//free all the nodes that were created and added to list
//if start is null, list is empty
if(start!=NULL)
{
Node *p,*q;
p=start;
while(p!=NULL)
{
q=p->next; //store the next node address before deleting the current node
delete p;
p=q;
}
}
}
//insert a node in the beginning of list. if list was empty, the new node becomes start
bool insertAtFront(Node *p)
{
if(p==NULL) //if null is received to be added , dont do anything and return false
return false;
//check if the list already has a start node, if ther is , make p point to the current start node
and then change p as the new start node
//if no start was there in the beginnning , then p will itself be the start node.
if(start==NULL)
start=p;
else
{
p->next=start;
start=p;
}
return true;
}
//inserts a node before a given index position, if index is 1, then the new node becomes the
start node, if index is out of range, node is not added
bool insertBeforePosition(int index,Node *p)
{
if(start==NULL || p==NULL)
{
return false;
}
else
{
Node *idxNode=start,*prev=NULL;
int i=1;
//traverse the list till we reach the index node and also keep track of the node previous
to index
while(inext;
i++;
}
if(idxNode==NULL)
{
//already the end of list is reached before the given index position is , i.e. index out
of range of list elements, so dont add
return false;
}
else
{
//since p will be at the given index, make p point to the old index node and also the
previous node to index point to p
p->next=idxNode;
if(prev==NULL) //means inserting in the beginning of list i.e index=1, so no
previous, so update start to teh new node
start=p;
else
prev->next=p;
return true;
}
}
}
//inserts the given node at the end of the list
bool insertAtBack(Node *p)
{
if(p==NULL)
return false;
if(start==NULL) //nothing in list , so p will be start
start=p;
else
{
Node *temp=start;
//go till the last node in the list, i.e the node which points to NULL is the last node
while(temp->next!=NULL)
temp=temp->next;
temp->next=p;
}
return true;
}
bool deleteAtFront()
{
if(start==NULL)
return false;
else
{
//to delete in front, simple make start of the list to point to its next node and free the
previous start node
Node *p=start;
start=p->next;
delete p;
}
return true;
}
bool deleteAtBack()
{
//to delete at back, go to end of the list and also keep track at last but one node. Free the
last node and update the last but one node to point to null
if(start==NULL)
return false;
else
{
Node *last=start,*lastButOne=NULL;
while(last->next!=NULL)
{
lastButOne=last;
last=last->next;
}
if(lastButOne==NULL)//means only one node in the list
start=NULL; //update start
else
{
lastButOne->next=NULL;
delete last;
}
}
return true;
}
//generally delete is specified aat a position, but the question says deleteBeforePosition(). So
coding for delete Before a index position
bool deleteBeforePosition(int index)
{
//cannont delete an empty list or before position 1
if(start==NULL || index ==1)
return false;
else
{
Node *prev=start,*idxNode=prev->next,*q=NULL;
int i=1;
while(inext;
i++;
}
//you have to delete previous node to index postiion, so if prev node was start node,
update start to point to new start
if(prev==start)
{
start=idxNode;
}
else
{
if(q!=NULL)
{
q->next=idxNode;
}
}
delete prev;
}
return true;
}
//+ operator will implement union of 2 lists. Since its not mentioned in list if the repeating
elements should be removed or left as is,
//following the general convention of having only one occurence of a element if repeatition
occurs
LinkedList operator +(LinkedList &list)
{
LinkedList newList;
Node *p=start,temp;
while(p!=NULL)
{
//add to list if only data is not in list already. because union means only once the
element appears from both list
//**********comment this if() condition line if data should be simply added without
checking if repeation occurs
if(newList.findData(p->data)==-1)
{
Node *q=new Node();
q->data=p->data;
q->next=NULL;
newList.insertAtBack(q);
}
p=p->next;
}
//add elents from second list
p=list.start;
while(p!=NULL)
{
//add to list if only data is not in list already. because union means only once the
element appears from both list
//**********comment this if() condition line if data should be simply added without
checking if repeation occurs
if(newList.findData(p->data)==-1)
{
Node *q=new Node();
q->data=p->data;
q->next=NULL;
newList.insertAtBack(q);
}
p=p->next;
}
return newList;
}
//a function to return the index position of the first occurence of the data in the list; returns -1
if not present otherwise return index
int findData(char data)
{
if(start==NULL)
return -1;
else
{
Node *q=start;
int index=1;
while(q!=NULL && q->data!=data)
{
q=q->next;
index++;
}
if(q==NULL) //reached end of list without finding the elemenet
return -1;
else
return index;
}
}
//- operator will implement difference of 2 lists. All elements in list 1 that are not in list 2
will be the result
LinkedList operator -( LinkedList &list)
{
LinkedList newList;
Node *p=start,temp;
while(p!=NULL)
{
//add to list if only data is not in 2nd list.
if(list.findData(p->data)==-1)
{
Node *q=new Node();
q->data=p->data;
q->next=NULL;
newList.insertAtBack(q);
}
p=p->next;
}
return newList;
}
void display()
{
Node *p=start;
cout<<" ";
while(p!=NULL)
{
cout<data<<" ";
p=p->next;
}
cout<<" ";
}
};
int main()
{
ifstream file;
char buffer[256];
int line =0;
LinkedList list[2];
//============REPLACE WITH CORRECT FILEPATH,
//can use forward slash / like in linux /home/user/sample.txt
file.open("c:testinput.txt");
/* if fopen( ) was not successful there was an error, so exit */
if(!file.is_open())
{
cout<<"Error opening file !";
return(1);
}
while(!file.eof() && line<2)
{
file.getline(buffer,256);
for(int i=0;buffer[i]!='0';i++)
{
Node *p=new Node();
p->data=buffer[i];
p->next=NULL;
list[line].insertAtBack(p);
}
line++;
}
cout<<"List 1:";
list[0].display();
cout<<" List 2:";
list[1].display();
LinkedList sum=list[0]+list[1],diff=list[0]-list[1];
cout<<" List 1 + List 2:";
sum.display();
cout<<" List 1 - List 2:";
diff.display();
/* Just testing different functions here to play around the list
All the functions are working as intended.
Node *p=new Node();
p->data='Z';
p->next=NULL;
list[0].insertAtFront(p);
list[1].deleteAtFront();
list[1].deleteAtBack();
p=new Node();
p->data='Y';
p->next=NULL;
list[0].insertBeforePosition(2,p);
list[1].deleteBeforePosition(3);
list[0].display();
list[1].display(); */
}
================
input.txt
=======
abcdefg
hijaklmnbopqc
====================
output:
=======
List 1:
a b c d e f g
List 2:
h i j a k l m n b o p q c
List 1 + List 2:
a b c d e f g h i j k l m n o p q
List 1 - List 2:
d e f g

More Related Content

Similar to Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf

This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfEricvtJFraserr
 
please i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfplease i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfezonesolutions
 
public class ThreeTenDLList-T- implements Iterable-T- { -- doubly.docx
public class ThreeTenDLList-T- implements Iterable-T- {      -- doubly.docxpublic class ThreeTenDLList-T- implements Iterable-T- {      -- doubly.docx
public class ThreeTenDLList-T- implements Iterable-T- { -- doubly.docxLukeQVdGrantg
 
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdfNeed Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdfEdwardw5nSlaterl
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfclearvisioneyecareno
 
In C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfIn C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfflashfashioncasualwe
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.pptWaf1231
 
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdf
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdfImplement the interface you wrote for Lab B (EntryWayListInterface)..pdf
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdfrishabjain5053
 
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdfDividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdftesmondday29076
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfSTAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfbabitasingh698417
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfannaelctronics
 
Consider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfConsider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfsales98
 
Describe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdfDescribe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdfdeepak596396
 

Similar to Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf (20)

Algo>ADT list & linked list
Algo>ADT list & linked listAlgo>ADT list & linked list
Algo>ADT list & linked list
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
 
please i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfplease i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdf
 
Ds notes
Ds notesDs notes
Ds notes
 
Linked lists a
Linked lists aLinked lists a
Linked lists a
 
public class ThreeTenDLList-T- implements Iterable-T- { -- doubly.docx
public class ThreeTenDLList-T- implements Iterable-T- {      -- doubly.docxpublic class ThreeTenDLList-T- implements Iterable-T- {      -- doubly.docx
public class ThreeTenDLList-T- implements Iterable-T- { -- doubly.docx
 
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdfNeed Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
 
Chapter14
Chapter14Chapter14
Chapter14
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
 
In C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfIn C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdf
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.ppt
 
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdf
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdfImplement the interface you wrote for Lab B (EntryWayListInterface)..pdf
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdf
 
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdfDividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfSTAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdf
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
 
Consider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfConsider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdf
 
Adt of lists
Adt of listsAdt of lists
Adt of lists
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
 
2.ppt
2.ppt2.ppt
2.ppt
 
Describe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdfDescribe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdf
 

More from ezzi97

Explain why multiple processes cannot share data easilySolution.pdf
Explain why multiple processes cannot share data easilySolution.pdfExplain why multiple processes cannot share data easilySolution.pdf
Explain why multiple processes cannot share data easilySolution.pdfezzi97
 
executive summary for law enforcement using dronesSolutionUse .pdf
executive summary for law enforcement using dronesSolutionUse .pdfexecutive summary for law enforcement using dronesSolutionUse .pdf
executive summary for law enforcement using dronesSolutionUse .pdfezzi97
 
Discuss how your life and experience with social mediaweb 2.0 compa.pdf
Discuss how your life and experience with social mediaweb 2.0 compa.pdfDiscuss how your life and experience with social mediaweb 2.0 compa.pdf
Discuss how your life and experience with social mediaweb 2.0 compa.pdfezzi97
 
create a narrative budget blueprint for a local unit of government. .pdf
create a narrative budget blueprint for a local unit of government. .pdfcreate a narrative budget blueprint for a local unit of government. .pdf
create a narrative budget blueprint for a local unit of government. .pdfezzi97
 
define three types of kernal-mode to user mode transfersSolution.pdf
define three types of kernal-mode to user mode transfersSolution.pdfdefine three types of kernal-mode to user mode transfersSolution.pdf
define three types of kernal-mode to user mode transfersSolution.pdfezzi97
 
Arrange the steps of DNA replication in the order that they occur. D.pdf
Arrange the steps of DNA replication in the order that they occur.  D.pdfArrange the steps of DNA replication in the order that they occur.  D.pdf
Arrange the steps of DNA replication in the order that they occur. D.pdfezzi97
 
C++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfC++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfezzi97
 
(c) After conducting several measurements, the Beijing Municipal Env.pdf
(c) After conducting several measurements, the Beijing Municipal Env.pdf(c) After conducting several measurements, the Beijing Municipal Env.pdf
(c) After conducting several measurements, the Beijing Municipal Env.pdfezzi97
 
1. Which of the following statements would correctly print out t.pdf
1. Which of the following statements would correctly print out t.pdf1. Which of the following statements would correctly print out t.pdf
1. Which of the following statements would correctly print out t.pdfezzi97
 
2.How important is it to involve physicians in financial improvement.pdf
2.How important is it to involve physicians in financial improvement.pdf2.How important is it to involve physicians in financial improvement.pdf
2.How important is it to involve physicians in financial improvement.pdfezzi97
 
Write one page essay to explain how you relate signals and systems t.pdf
Write one page essay to explain how you relate signals and systems t.pdfWrite one page essay to explain how you relate signals and systems t.pdf
Write one page essay to explain how you relate signals and systems t.pdfezzi97
 
Why do IDPs & IDRs lack structure Lack a ligand or partner Denatu.pdf
Why do IDPs & IDRs lack structure  Lack a ligand or partner  Denatu.pdfWhy do IDPs & IDRs lack structure  Lack a ligand or partner  Denatu.pdf
Why do IDPs & IDRs lack structure Lack a ligand or partner Denatu.pdfezzi97
 
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdf
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdfWrite 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdf
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdfezzi97
 
Why is methyl salicylate not appreciably soluble in waterSoluti.pdf
Why is methyl salicylate not appreciably soluble in waterSoluti.pdfWhy is methyl salicylate not appreciably soluble in waterSoluti.pdf
Why is methyl salicylate not appreciably soluble in waterSoluti.pdfezzi97
 
Who are stakeholders Define who they are and then please share what.pdf
Who are stakeholders Define who they are and then please share what.pdfWho are stakeholders Define who they are and then please share what.pdf
Who are stakeholders Define who they are and then please share what.pdfezzi97
 
What was the biggest problem with the Articles of Confederation They.pdf
What was the biggest problem with the Articles of Confederation They.pdfWhat was the biggest problem with the Articles of Confederation They.pdf
What was the biggest problem with the Articles of Confederation They.pdfezzi97
 
What is UWIN and what does it doSolutionUWin is a software .pdf
What is UWIN and what does it doSolutionUWin is a software .pdfWhat is UWIN and what does it doSolutionUWin is a software .pdf
What is UWIN and what does it doSolutionUWin is a software .pdfezzi97
 
What sort of archaeological remains have been discovered on the site.pdf
What sort of archaeological remains have been discovered on the site.pdfWhat sort of archaeological remains have been discovered on the site.pdf
What sort of archaeological remains have been discovered on the site.pdfezzi97
 
Link to assignment that I need help with is below httpweb.cse..pdf
Link to assignment that I need help with is below httpweb.cse..pdfLink to assignment that I need help with is below httpweb.cse..pdf
Link to assignment that I need help with is below httpweb.cse..pdfezzi97
 
The Food Stamp Program is Americas first line of defense against hu.pdf
The Food Stamp Program is Americas first line of defense against hu.pdfThe Food Stamp Program is Americas first line of defense against hu.pdf
The Food Stamp Program is Americas first line of defense against hu.pdfezzi97
 

More from ezzi97 (20)

Explain why multiple processes cannot share data easilySolution.pdf
Explain why multiple processes cannot share data easilySolution.pdfExplain why multiple processes cannot share data easilySolution.pdf
Explain why multiple processes cannot share data easilySolution.pdf
 
executive summary for law enforcement using dronesSolutionUse .pdf
executive summary for law enforcement using dronesSolutionUse .pdfexecutive summary for law enforcement using dronesSolutionUse .pdf
executive summary for law enforcement using dronesSolutionUse .pdf
 
Discuss how your life and experience with social mediaweb 2.0 compa.pdf
Discuss how your life and experience with social mediaweb 2.0 compa.pdfDiscuss how your life and experience with social mediaweb 2.0 compa.pdf
Discuss how your life and experience with social mediaweb 2.0 compa.pdf
 
create a narrative budget blueprint for a local unit of government. .pdf
create a narrative budget blueprint for a local unit of government. .pdfcreate a narrative budget blueprint for a local unit of government. .pdf
create a narrative budget blueprint for a local unit of government. .pdf
 
define three types of kernal-mode to user mode transfersSolution.pdf
define three types of kernal-mode to user mode transfersSolution.pdfdefine three types of kernal-mode to user mode transfersSolution.pdf
define three types of kernal-mode to user mode transfersSolution.pdf
 
Arrange the steps of DNA replication in the order that they occur. D.pdf
Arrange the steps of DNA replication in the order that they occur.  D.pdfArrange the steps of DNA replication in the order that they occur.  D.pdf
Arrange the steps of DNA replication in the order that they occur. D.pdf
 
C++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfC++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdf
 
(c) After conducting several measurements, the Beijing Municipal Env.pdf
(c) After conducting several measurements, the Beijing Municipal Env.pdf(c) After conducting several measurements, the Beijing Municipal Env.pdf
(c) After conducting several measurements, the Beijing Municipal Env.pdf
 
1. Which of the following statements would correctly print out t.pdf
1. Which of the following statements would correctly print out t.pdf1. Which of the following statements would correctly print out t.pdf
1. Which of the following statements would correctly print out t.pdf
 
2.How important is it to involve physicians in financial improvement.pdf
2.How important is it to involve physicians in financial improvement.pdf2.How important is it to involve physicians in financial improvement.pdf
2.How important is it to involve physicians in financial improvement.pdf
 
Write one page essay to explain how you relate signals and systems t.pdf
Write one page essay to explain how you relate signals and systems t.pdfWrite one page essay to explain how you relate signals and systems t.pdf
Write one page essay to explain how you relate signals and systems t.pdf
 
Why do IDPs & IDRs lack structure Lack a ligand or partner Denatu.pdf
Why do IDPs & IDRs lack structure  Lack a ligand or partner  Denatu.pdfWhy do IDPs & IDRs lack structure  Lack a ligand or partner  Denatu.pdf
Why do IDPs & IDRs lack structure Lack a ligand or partner Denatu.pdf
 
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdf
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdfWrite 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdf
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdf
 
Why is methyl salicylate not appreciably soluble in waterSoluti.pdf
Why is methyl salicylate not appreciably soluble in waterSoluti.pdfWhy is methyl salicylate not appreciably soluble in waterSoluti.pdf
Why is methyl salicylate not appreciably soluble in waterSoluti.pdf
 
Who are stakeholders Define who they are and then please share what.pdf
Who are stakeholders Define who they are and then please share what.pdfWho are stakeholders Define who they are and then please share what.pdf
Who are stakeholders Define who they are and then please share what.pdf
 
What was the biggest problem with the Articles of Confederation They.pdf
What was the biggest problem with the Articles of Confederation They.pdfWhat was the biggest problem with the Articles of Confederation They.pdf
What was the biggest problem with the Articles of Confederation They.pdf
 
What is UWIN and what does it doSolutionUWin is a software .pdf
What is UWIN and what does it doSolutionUWin is a software .pdfWhat is UWIN and what does it doSolutionUWin is a software .pdf
What is UWIN and what does it doSolutionUWin is a software .pdf
 
What sort of archaeological remains have been discovered on the site.pdf
What sort of archaeological remains have been discovered on the site.pdfWhat sort of archaeological remains have been discovered on the site.pdf
What sort of archaeological remains have been discovered on the site.pdf
 
Link to assignment that I need help with is below httpweb.cse..pdf
Link to assignment that I need help with is below httpweb.cse..pdfLink to assignment that I need help with is below httpweb.cse..pdf
Link to assignment that I need help with is below httpweb.cse..pdf
 
The Food Stamp Program is Americas first line of defense against hu.pdf
The Food Stamp Program is Americas first line of defense against hu.pdfThe Food Stamp Program is Americas first line of defense against hu.pdf
The Food Stamp Program is Americas first line of defense against hu.pdf
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Recently uploaded (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf

  • 1. Homework 05 - Linked Lists (C++) (1) Implement the concepts of a union, and difference as defined noted in Chapter 1 questions 6, and 8 using a linked list. You should not use arrays, dynamic arrays or the STL vector or STL list classes. You will be linking a series of nodes together to implement a single linked list class. Define a Node as a struct that holds a character (like they did in the book) and a pointer to another Node: struct Node { char data; Node* next; }; Then define a LinkedList class which has (at a minimum) these member functions: LinkedList(); ~LinkedList(); bool insertAtFront(); bool insertBeforePosition(int index); bool insertAtBack(); bool deleteAtFront(); bool deleteBeforePosition(int index); bool deleteAtBack(); Implement each of these functions to provide the correct functionality. These functions return true if successful in inserting or deleting, otherwise they return false (indicating the operation was not successful). Finally, create an overloaded + operator to handle the Union of two linked lists and an overloaded - operator to handle the Difference of two linked lists. Because we are dealing with pointers you should have both a LinkedList Constructor and Destructor. Remember that you do not directly call a Constructor or Destructor Function. The Destructor is automatically called when the variable loses scope or the program ends. Remember, that we are dealing with not just one dynamically allocated Node (with the new operator), but many, so you will have to start at the head of the list and go until the Node points to nullptr. Then keep deleting the previous Node pointer until there are no Nodes left to delete. (2) To verify your set class, write a main function that takes two lines of characters from the input file input.txt and store each line of characters into two separate linked lists. Then using these two lists, perform the Union and set Difference of the characters from the file, and print the results to the console. (3) Please also complete an asymptotic (Big O) analysis of your insertAtFront() and
  • 2. insertAtBack() member functions. Place this in a file called analysis.txt. Solution Here is the complete code for your question. Please do rate the aswer if you are happy with program. Please read comments in the program. Also pay special attention to comments in + and - operators. You WILL NEED to comment out if condition in + if you want all elements in both lists irrespective of if they duplicates or no. For now implemented to have true behaviour of no duplicates in union. check the functions by creating some lists and playing around different fucntions like its done in main and commented out. As far as complexity: for insertAtFront() its O(1) since it does not depend on the size of the list. It just replaces the start of the list. Hence it is O(1) and independent of the size of list. for insertAtBack(), its O(n) since it depends on the number of elements in the list. It should traverse till end of list and then insert. So it depends on list size and hence O(n). ======================================= #include #include using namespace std; struct Node { char data; Node *next; }; class LinkedList { Node *start; public: LinkedList() { //initialize to NULL since no nodes are in the list start=NULL; } //Destructor to free all nodes that were in the list ~LinkedList()
  • 3. { //free all the nodes that were created and added to list //if start is null, list is empty if(start!=NULL) { Node *p,*q; p=start; while(p!=NULL) { q=p->next; //store the next node address before deleting the current node delete p; p=q; } } } //insert a node in the beginning of list. if list was empty, the new node becomes start bool insertAtFront(Node *p) { if(p==NULL) //if null is received to be added , dont do anything and return false return false; //check if the list already has a start node, if ther is , make p point to the current start node and then change p as the new start node //if no start was there in the beginnning , then p will itself be the start node. if(start==NULL) start=p; else { p->next=start; start=p; } return true; } //inserts a node before a given index position, if index is 1, then the new node becomes the start node, if index is out of range, node is not added bool insertBeforePosition(int index,Node *p)
  • 4. { if(start==NULL || p==NULL) { return false; } else { Node *idxNode=start,*prev=NULL; int i=1; //traverse the list till we reach the index node and also keep track of the node previous to index while(inext; i++; } if(idxNode==NULL) { //already the end of list is reached before the given index position is , i.e. index out of range of list elements, so dont add return false; } else { //since p will be at the given index, make p point to the old index node and also the previous node to index point to p p->next=idxNode; if(prev==NULL) //means inserting in the beginning of list i.e index=1, so no previous, so update start to teh new node start=p; else prev->next=p; return true; } } } //inserts the given node at the end of the list bool insertAtBack(Node *p)
  • 5. { if(p==NULL) return false; if(start==NULL) //nothing in list , so p will be start start=p; else { Node *temp=start; //go till the last node in the list, i.e the node which points to NULL is the last node while(temp->next!=NULL) temp=temp->next; temp->next=p; } return true; } bool deleteAtFront() { if(start==NULL) return false; else { //to delete in front, simple make start of the list to point to its next node and free the previous start node Node *p=start; start=p->next; delete p; } return true; } bool deleteAtBack() { //to delete at back, go to end of the list and also keep track at last but one node. Free the last node and update the last but one node to point to null if(start==NULL) return false; else
  • 6. { Node *last=start,*lastButOne=NULL; while(last->next!=NULL) { lastButOne=last; last=last->next; } if(lastButOne==NULL)//means only one node in the list start=NULL; //update start else { lastButOne->next=NULL; delete last; } } return true; } //generally delete is specified aat a position, but the question says deleteBeforePosition(). So coding for delete Before a index position bool deleteBeforePosition(int index) { //cannont delete an empty list or before position 1 if(start==NULL || index ==1) return false; else { Node *prev=start,*idxNode=prev->next,*q=NULL; int i=1; while(inext; i++; } //you have to delete previous node to index postiion, so if prev node was start node, update start to point to new start if(prev==start) { start=idxNode;
  • 7. } else { if(q!=NULL) { q->next=idxNode; } } delete prev; } return true; } //+ operator will implement union of 2 lists. Since its not mentioned in list if the repeating elements should be removed or left as is, //following the general convention of having only one occurence of a element if repeatition occurs LinkedList operator +(LinkedList &list) { LinkedList newList; Node *p=start,temp; while(p!=NULL) { //add to list if only data is not in list already. because union means only once the element appears from both list //**********comment this if() condition line if data should be simply added without checking if repeation occurs if(newList.findData(p->data)==-1) { Node *q=new Node(); q->data=p->data; q->next=NULL; newList.insertAtBack(q); } p=p->next; } //add elents from second list
  • 8. p=list.start; while(p!=NULL) { //add to list if only data is not in list already. because union means only once the element appears from both list //**********comment this if() condition line if data should be simply added without checking if repeation occurs if(newList.findData(p->data)==-1) { Node *q=new Node(); q->data=p->data; q->next=NULL; newList.insertAtBack(q); } p=p->next; } return newList; } //a function to return the index position of the first occurence of the data in the list; returns -1 if not present otherwise return index int findData(char data) { if(start==NULL) return -1; else { Node *q=start; int index=1; while(q!=NULL && q->data!=data) { q=q->next; index++; } if(q==NULL) //reached end of list without finding the elemenet return -1; else
  • 9. return index; } } //- operator will implement difference of 2 lists. All elements in list 1 that are not in list 2 will be the result LinkedList operator -( LinkedList &list) { LinkedList newList; Node *p=start,temp; while(p!=NULL) { //add to list if only data is not in 2nd list. if(list.findData(p->data)==-1) { Node *q=new Node(); q->data=p->data; q->next=NULL; newList.insertAtBack(q); } p=p->next; } return newList; } void display() { Node *p=start; cout<<" "; while(p!=NULL) { cout<data<<" "; p=p->next; } cout<<" "; } };
  • 10. int main() { ifstream file; char buffer[256]; int line =0; LinkedList list[2]; //============REPLACE WITH CORRECT FILEPATH, //can use forward slash / like in linux /home/user/sample.txt file.open("c:testinput.txt"); /* if fopen( ) was not successful there was an error, so exit */ if(!file.is_open()) { cout<<"Error opening file !"; return(1); } while(!file.eof() && line<2) { file.getline(buffer,256); for(int i=0;buffer[i]!='0';i++) { Node *p=new Node(); p->data=buffer[i]; p->next=NULL; list[line].insertAtBack(p); } line++; } cout<<"List 1:"; list[0].display(); cout<<" List 2:"; list[1].display(); LinkedList sum=list[0]+list[1],diff=list[0]-list[1]; cout<<" List 1 + List 2:"; sum.display(); cout<<" List 1 - List 2:"; diff.display();
  • 11. /* Just testing different functions here to play around the list All the functions are working as intended. Node *p=new Node(); p->data='Z'; p->next=NULL; list[0].insertAtFront(p); list[1].deleteAtFront(); list[1].deleteAtBack(); p=new Node(); p->data='Y'; p->next=NULL; list[0].insertBeforePosition(2,p); list[1].deleteBeforePosition(3); list[0].display(); list[1].display(); */ } ================ input.txt ======= abcdefg hijaklmnbopqc ==================== output: ======= List 1: a b c d e f g List 2: h i j a k l m n b o p q c List 1 + List 2: a b c d e f g h i j k l m n o p q List 1 - List 2: d e f g