In: Computer Science
C++ ONLY -- LAB ASSIGNMENT DIFFICULT
We have to turn in two files - List.h and Lab5.cpp
What should the code for those two files look like?
INSTRUCTIONS AS FOLLOWS:
What Should This Program Do?
Linked List Class
DRIVER – Lab5.cpp
Write a driver program (Lab5.cpp) that will do the following:
PROGRAM :
List.h
#ifndef LIST_H
#define LIST_H
#include<string>
#include<iostream>
using namespace std;
struct Node
{
string data;
Node *next;
};
class List
{
public:
List();
void appending(string);
void inserting(string);
void deleting(string);
void print();
private:
Node * head;
Node * tail;
};
#endif
List.cpp implementation file
#include"List.h"
List::List()
{
head = NULL;
tail = NULL;
cout << "The linked list has been created." <<
endl;
}
void List::appending(string data)
{
Node *newNode = new Node();
newNode->data = data;
newNode->next = NULL;
if (head == NULL)
{
head = tail=newNode;
return;
}
tail->next = newNode;
tail = newNode;
}
void List::inserting(string data)
{
Node *newNode = new Node();
newNode->data = data;
newNode->next = NULL;
if (head == NULL)
{
head = tail = newNode;
return;
}
if (head->data > data)
{
newNode->next = head;
head = newNode;
}
if (tail->data < data)
{
tail->next = newNode;
tail = newNode;
}
Node *curr = head;
Node *prev = head;
while (curr != tail)
{
if (curr->data > data)
break;
prev = curr;
curr = curr->next;
}
prev->next = newNode;
newNode->next = curr;
}
void List::print()
{
Node *temp=head;
while (temp)
{
cout << temp->data << endl;
temp = temp->next;
}
}
void List::deleting(string data)
{
if (head == NULL)
{
return;
}
if (head->data == data)
{
Node *temp = head;
head = head->next;
delete temp;
}
Node *curr = head;
Node *prev = head;
while (curr != tail)
{
if (curr->data == data)
break;
prev = curr;
curr = curr->next;
}
prev->next = curr->next;
}
Lab5.cpp
#include"List.h"
int main()
{
List lst;
cout << "I am appending several strings to the list."
<< endl;
lst.appending("boogeyman");
lst.appending("ghost");
lst.appending("scarecrow");
lst.appending("witch");
lst.appending("zombie");
lst.print();
cout << "I am inserting vampire in the list." <<
endl;
lst.inserting("vampire");
lst.print();
cout << "I am deleting ghost from the list." <<
endl;
lst.deleting("ghost");
lst.print();
system("pause");
}
OUTPUT :