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 .
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