SlideShare une entreprise Scribd logo
1  sur  24
//driver.cpp
//written to test doubly-linked list ADT
//ItemType must have << and >> operators defined
#include <fstream>
#include <iostream>
#include <string>
#include "sortlist.h"
using namespace std;
template <class ItemType>
void PrintAscending(ostream& dataFile,
SortedType<ItemType>& list, string listName);
//pre: list has been initialized
// dataFile is open for output
//post: each component in list has been written to
dataFile
// dataFile is still open
template <class ItemType>
void PrintDescending(ostream& dataFile,
SortedType<ItemType>& list, string listName);
//pre: list has been initialized
// dataFile is open for output
//post: each component in list has been written, in
reverse order, to dataFile
// dataFile is still open
void DisplayMenu(int& choice);
//pre: listA and listB have been initialized
//post: displays a menu for list operations
template <class ItemType>
void Insert(SortedType<ItemType>& list, string
listName);
//pre: list has been initialized
// item to insert is entered by the user in the
function
//post: Calls the ADT InsertItem and prints a message
indicating
// success or failure
template <class ItemType>
void Delete(SortedType<ItemType>& list, string
listName);
//pre: list has been initialized
// item to delete is entered by the user within
the function
//post: Calls the ADT delete function and prints a
message
// indicating success or failure.
template <class ItemType>
void Retrieve(SortedType<ItemType> list);
//pre: none
//post: prompts user for item to retrieve from list;
displays message
// indicating whether or not item was found in
the list
int main()
{
SortedType<int> listA, listB, listC;
int choice;
while (true)
{
DisplayMenu(choice);
switch (choice)
{
case 0: return 0;
case 1: Insert(listA, "A");
break;
case 2: Insert(listB, "B");
break;
case 3: Delete(listA, "A");
break;
case 4: listA.MakeEmpty();
break;
case 5: Retrieve(listA);
break;
case 6: listC = listB = listA;
break;
case 7: listA.RemoveFirst();
break;
case 8: listA.RemoveLast();
break;
case 9: PrintAscending(cout, listA,
"A");
PrintAscending(cout, listB,
"B");
PrintAscending(cout, listC,
"C");
break;
case 10: PrintDescending(cout, listA,
"A");
PrintDescending(cout, listB,
"B");
PrintDescending(cout, listC,
"C");
break;
default: return 0;
}//end switch
}//end while
}//end main
template <class ItemType>
void PrintAscending(ostream& dataFile,
SortedType<ItemType>& list, string listName)
{
ItemType item;
int length = list.LengthIs();
if (length == 0)
{
dataFile << "List " << listName << " is
empty.n";
return;
}
dataFile << "List " << listName << " contains the
following items:n";
list.ResetList();
for (int count=0; count<length; count++)
{
list.GetNextItem(item);
dataFile << item;
dataFile << " ";
}
dataFile << endl;
}
template <class ItemType>
void PrintDescending(ostream& dataFile,
SortedType<ItemType>& list, string listName)
{
ItemType item;
int length = list.LengthIs();
if (length == 0)
{
dataFile << "List " << listName << " is
empty.n";
return;
}
dataFile << "List " << listName << " contains the
following items:n";
list.ResetListBackward();
for (int count=0; count<length; count++)
{
list.GetPreviousItem(item);
dataFile << item;
dataFile << " ";
}
dataFile << endl;
}
void DisplayMenu(int& choice)
{
cout << "Please select from the menu.nn";
cout << "1tInsert an item to List A.n";
cout << "2tInsert an item to List B.n";
cout << "3tDelete an item from List A.n";
cout << "4tDelete all items from List A. (Make
listA empty)n";
cout << "5tRetrieve an item from List A.n";
cout << "6tPerform assignment: listC = listB =
listAn";
cout << "7tDelete first element of List A.n";
cout << "8tDelete last element of List A.n";
cout << "9tPrint lists in ascending order.n";
cout << "10tPrint lists in descending order.n";
cout << "0tExit programnn";
cin >> choice;
}
template <class ItemType>
void Insert(SortedType<ItemType>& list, string
listName)
{
ItemType item;
cout << "Please enter the item to insert: ";
cin >> item;
if (list.InsertItem(item))
cout << item << " has been inserted into list
" << listName << ".n";
else
cout << "Unable to add " << item << " to " <<
listName << ".n";
}
template <class ItemType>
void Delete(SortedType<ItemType>& list, string
listName)
{
ItemType item;
cout << "Please enter the item to delete: ";
cin >> item;
if (list.DeleteItem(item))
cout << item << " has been deleted from list
" << listName << ".n";
else
cout << item << " was not in the list. List
has not been changed.n";
}
template <class ItemType>
void Retrieve(SortedType<ItemType> list)
{
ItemType item;
bool found;
cout << "Please enter the item to be
retrieved:n";
cin >> item;
list.RetrieveItem(item, found);
if (found)
cout << item << " was in the list.n";
else
cout << item << " was not in the list.n";
}
// Implementation file for Sorted List ADT.
// Class specification is in file sortlist.h.
// Class is templated.
template<class ItemType>
struct NodeType
{
ItemType info;
NodeType* next;
NodeType* back;
};
template <class ItemType>
SortedType<ItemType>::SortedType ()
{
length = 0;
listData = NULL;
listRear = NULL;
}
template <class ItemType>
SortedType<ItemType>::~SortedType ()
{
NodeType<ItemType>* tempPtr;
while(listData != NULL)
{
tempPtr = listData;
listData = listData->next;
delete tempPtr;
}
}
template <class ItemType>
SortedType<ItemType>::SortedType(const SortedType&
source)
{
//initialize variables
length = 0;
currentPos = NULL;
listData = NULL;
listRear = NULL;
NodeType<ItemType>* sourcePtr;
NodeType<ItemType>* newNodePtr;
//copy nodes from rhs
sourcePtr = source.listData;
while (sourcePtr != NULL)
{
newNodePtr = new NodeType<ItemType>;
newNodePtr->info = sourcePtr->info;
if (listData == NULL) //first node to be
copied
{
listData = newNodePtr;
listRear = newNodePtr;
newNodePtr->next = NULL;
newNodePtr->back = NULL;
}
else
{
listRear->next = newNodePtr;
newNodePtr->back = listRear;
newNodePtr->next = NULL;
listRear = newNodePtr;
}
length++;
sourcePtr = sourcePtr->next;
}
}
template <class ItemType>
SortedType<ItemType> SortedType<ItemType>::operator
=(const SortedType& rhs)
{
//check x=x case
if (this == &rhs)
return(*this);
//delete existing list before assigning it the
values in rtList
NodeType<ItemType>* lhsPtr;
NodeType<ItemType>* rhsPtr;
while (listData != NULL)
{
lhsPtr = listData;
listData = listData->next;
delete lhsPtr;
}
length = 0;
listRear = NULL;
//copy nodes from rhs
rhsPtr = rhs.listData;
while (rhsPtr != NULL)
{
lhsPtr = new NodeType<ItemType>;
lhsPtr->info = rhsPtr->info;
if (listData == NULL) //first node to be
copied
{
listData = lhsPtr;
listRear = lhsPtr;
lhsPtr->next = NULL;
lhsPtr->back = NULL;
}
else
{
listRear->next = lhsPtr;
lhsPtr->back = listRear;
lhsPtr->next = NULL;
listRear = lhsPtr;
}
length++;
rhsPtr = rhsPtr->next;
}
return (*this);
}
template <class ItemType>
bool SortedType<ItemType>::IsFull() const
{
NodeType<ItemType>* ptr;
ptr = new NodeType<ItemType>;
if (ptr == NULL)
return true;
else
{
delete ptr;
return false;
}
}
template <class ItemType>
int SortedType<ItemType>::LengthIs() const
{
return length;
}
template <class ItemType>
void SortedType<ItemType>::MakeEmpty()
{
NodeType<ItemType>* tempPtr;
while (listData != NULL)
{
tempPtr = listData;
listData = listData->next;
delete tempPtr;
}
listRear = NULL;
length = 0;
}
template <class ItemType>
void SortedType<ItemType>::RetrieveItem(ItemType&
item, bool& found)
{
bool moreToSearch;
NodeType<ItemType>* location;
location = listData;
found = false;
moreToSearch = (location != NULL);
while (moreToSearch && !found)
{
if (location->info < item)
{
location = location->next;
moreToSearch = (location != NULL);
}
else if (item == location->info)
{
found = true;
item = location->info;
}
else
moreToSearch = false;
}
}
template <class ItemType>
bool SortedType<ItemType>::InsertItem(ItemType item)
{
//modify the following code so that the function
returns false
//if item is already in the list
//Prepare node for insertion
NodeType<ItemType>* newNode;
newNode = new NodeType<ItemType>;
if (newNode == NULL)
return false;
newNode->info = item;
//check if inserting into empty list
if (listData == NULL)
{
newNode->next = NULL;
newNode->back = NULL;
listData = newNode;
listRear = newNode;
}
else if(item ==listData->info)
return false;
//check if inserting before existing first item
else if (item < listData->info)
{
newNode->next = listData;
newNode->back = NULL;
listData->back = newNode;
listData = newNode;
}
//check if inserting after last item
else if (item > listRear->info)
{
newNode->next = NULL;
newNode->back = listRear;
listRear->next = newNode;
listRear = newNode;
}
else//inserting between existing nodes
{
// Find node that should precede newNode
NodeType<ItemType>* location;
location = listData;
while (location->next->info < item)
location = location->next;
if(location->next->info == item)
return false;
else
{
//insert node into list.
newNode->back = location;
newNode->next = location->next;
location->next->back = newNode;
location->next = newNode;
}
}
length++;
return true;
}
template <class ItemType>
void SortedType<ItemType>::RemoveFirst()
{
if(listData == NULL)
return;
NodeType<ItemType>* tempPtr = listData;
if(listData->next == NULL)
{
delete tempPtr;
listData = NULL;
listRear = NULL;
length = 0;
}
else
{
listData = listData->next;
listData->back = NULL;
delete tempPtr;
length--;
}
}
template <class ItemType>
void SortedType<ItemType>::RemoveLast()
{
if(listData == NULL)
return;
NodeType<ItemType>* tempPtr = listRear;
if(listData->next == NULL)
{
delete tempPtr;
listData = NULL;
listRear = NULL;
length = 0;
}
else
{
listRear = listRear->back;
listRear->next = NULL;
delete tempPtr;
length--;
}
}
template <class ItemType>
bool SortedType<ItemType>::DeleteItem(ItemType item)
{
if(listData == NULL)
return false;
NodeType<ItemType>* tempPtr = listData;
if(item == listData->info)
{
if(listData->next == NULL)
{
delete tempPtr;
listData = NULL;
listRear = NULL;
length = 0;
}
else
{
listData = listData->next;
listData->back = NULL;
delete tempPtr;
length--;
}
}
else if(item == listRear->info)
{
tempPtr =listRear;
listRear =listRear->back;
listRear->next = NULL;
delete tempPtr;
length--;
}
else
{
while(tempPtr->next->info != item)
{
if(tempPtr->next->info > item)
return false;
else
tempPtr = tempPtr->next;
}
NodeType<ItemType>* newNode;
newNode = tempPtr->next;
tempPtr->next = newNode->next;
newNode->next->back = tempPtr;
delete newNode;
length--;
}
return true;
}
template <class ItemType>
void SortedType<ItemType>::ResetList()
{
currentPos = NULL;
}
template <class ItemType>
void SortedType<ItemType>::ResetListBackward()
{
currentRev = NULL;
}
template <class ItemType>
void SortedType<ItemType>::GetNextItem(ItemType&
item)
{
if (currentPos == NULL)
currentPos = listData;
else
currentPos = currentPos->next;
item = currentPos->info;
}
template <class ItemType>
void SortedType<ItemType>::GetPreviousItem(ItemType&
item)
{
if (currentRev == NULL)
currentRev = listRear;
else
currentRev = currentRev->back;
item = currentRev->info;
}
// sortlist.h: Header file for Sorted List ADT.
// Class is templated.
// Assumption: ItemType is a type for which the
comparison operators
// are defined
#ifndef SORTLIST_H
#define SORTLIST_H
template <class ItemType>
struct NodeType;
template <class ItemType>
class SortedType
{
public:
SortedType (); // Class constructor
~SortedType (); // Class destructor
SortedType(const SortedType& source);
//copy constructor
SortedType operator =(const SortedType& rhs);
//assignment operator
bool IsFull() const;
// Function: Determines whether list is full.
// Post: Function value = (list is full)
int LengthIs() const;
// Function: Determines the number of elements in
list.
// Post: Function value = number of elements in
list.
void MakeEmpty();
// Function: Initializes list to empty state.
// Post: List is empty.
void RetrieveItem(ItemType& item, bool& found);
// Function: Retrieves list element whose key
matches item's key (if present).
// Pre: Key member of item is initialized.
// Post: If there is an element someItem whose
key matches item's key,
// then found = true and item is a copy of
someItem; otherwise
// found = false and item is unchanged.
// List is unchanged.
bool InsertItem(ItemType item);
// Function: Adds item to list
// Pre: List has been initialized
// Post: Returns true if the item was
successfully added
// returns false if not able to add
void RemoveFirst();
//pre: none
//post: if list is not empty, first element has
been removed,
// else list is unchanged
void RemoveLast();
//pre: none
//post: if list is not empty, last element has
been removed,
// else list is unchanged
bool DeleteItem(ItemType item);
// Function: Deletes the element whose key
matches item's key.
// Pre: Key member of item is initialized.
// At most one element in list has a key
matching item's key.
// Post: No element in list has a key matching
item's key.
void ResetList();
// Function: Initializes current position for an
iteration through the list.
// Pre: List has been initialized
// Post: Current position is prior to first
element of list.
void GetNextItem(ItemType&);
// Function: Gets the next element in list.
// Pre: Current position is defined.
// Element at current position is not last
in list.
// Post: Current position is updated to next
position.
// item is a copy of element at current
position.
void ResetListBackward();
// Function: Initializes current position for a
backward iteration through the list.
// Pre: List has been initialized
// Post: Current position is after the last
element of the list
void GetPreviousItem(ItemType&);
// Function: Gets the previous element in list.
// Pre: Current position is defined.
// Element at current position is not first
in list.
// Post: Current position is updated to previous
position.
// item is a copy of element at current
position.
private:
int length;
NodeType<ItemType>* listData;
NodeType<ItemType>* listRear;
NodeType<ItemType>* currentPos; //for forward
traversal
NodeType<ItemType>* currentRev; //for backward
traversal
};
#include "sortlist.cpp"
#endif

Contenu connexe

Tendances (19)

supporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered tablesupporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered table
 
Chapter 5 Class File
Chapter 5 Class FileChapter 5 Class File
Chapter 5 Class File
 
Linked list1
Linked list1Linked list1
Linked list1
 
Fp java8
Fp java8Fp java8
Fp java8
 
Groovy
GroovyGroovy
Groovy
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
Assignment
AssignmentAssignment
Assignment
 
jQuery
jQueryjQuery
jQuery
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java collection
Java collectionJava collection
Java collection
 
Generics
GenericsGenerics
Generics
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
 
07 java collection
07 java collection07 java collection
07 java collection
 
JDK 8
JDK 8JDK 8
JDK 8
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 

En vedette (20)

Formato manual de sistemas
Formato manual de sistemasFormato manual de sistemas
Formato manual de sistemas
 
kasur comforta
kasur comfortakasur comforta
kasur comforta
 
Deportes
DeportesDeportes
Deportes
 
Amparo1
Amparo1Amparo1
Amparo1
 
Hoja de vida
Hoja de vidaHoja de vida
Hoja de vida
 
30° anniversario Gemellaggio Pisa-Angers
30° anniversario Gemellaggio Pisa-Angers30° anniversario Gemellaggio Pisa-Angers
30° anniversario Gemellaggio Pisa-Angers
 
36x60 horizontal templatev12
36x60 horizontal templatev1236x60 horizontal templatev12
36x60 horizontal templatev12
 
Blog origami
Blog origamiBlog origami
Blog origami
 
Sj2powerpoint
Sj2powerpointSj2powerpoint
Sj2powerpoint
 
Audio saia
Audio saiaAudio saia
Audio saia
 
Abstract nature pdf
Abstract nature pdfAbstract nature pdf
Abstract nature pdf
 
Guía de historia universal
Guía de historia universalGuía de historia universal
Guía de historia universal
 
Radical pre quiz
Radical pre quizRadical pre quiz
Radical pre quiz
 
My linked in_video
My linked in_videoMy linked in_video
My linked in_video
 
E portafolio
E portafolioE portafolio
E portafolio
 
Diversidad
DiversidadDiversidad
Diversidad
 
Ios
Ios Ios
Ios
 
Biblioteca+reflexiones power
Biblioteca+reflexiones powerBiblioteca+reflexiones power
Biblioteca+reflexiones power
 
Paginas web
Paginas webPaginas web
Paginas web
 
Carlincaturas
CarlincaturasCarlincaturas
Carlincaturas
 

Similaire à C++ detyrat postim_slideshare

BackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdfBackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdfmayorothenguyenhob69
 
Using the C++ programming language1. Implement the UnsortedList cl.pdf
Using the C++ programming language1. Implement the UnsortedList cl.pdfUsing the C++ programming language1. Implement the UnsortedList cl.pdf
Using the C++ programming language1. Implement the UnsortedList cl.pdfmallik3000
 
This is the main file include itemh include itemList.pdf
This is the main file include itemh include itemList.pdfThis is the main file include itemh include itemList.pdf
This is the main file include itemh include itemList.pdfinfo334223
 
Write a program to find the number of comparisons using the binary se.docx
 Write a program to find the number of comparisons using the binary se.docx Write a program to find the number of comparisons using the binary se.docx
Write a program to find the number of comparisons using the binary se.docxajoy21
 
Implement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdfImplement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdfpetercoiffeur18
 
-- Reminder that your file name is incredibly important- Please do not.docx
-- Reminder that your file name is incredibly important- Please do not.docx-- Reminder that your file name is incredibly important- Please do not.docx
-- Reminder that your file name is incredibly important- Please do not.docxAdamq0DJonese
 
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdfganisyedtrd
 
In C pls -- Write your name here -- Write the compiler used- Visual st.docx
In C pls -- Write your name here -- Write the compiler used- Visual st.docxIn C pls -- Write your name here -- Write the compiler used- Visual st.docx
In C pls -- Write your name here -- Write the compiler used- Visual st.docxBlake0FxCampbelld
 
Pleae help me with this C++ question, ill upvote thanks.Write the .pdf
Pleae help me with this C++ question, ill upvote thanks.Write the .pdfPleae help me with this C++ question, ill upvote thanks.Write the .pdf
Pleae help me with this C++ question, ill upvote thanks.Write the .pdfvinodagrawal6699
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
 
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfComplete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfrajkumarm401
 
please follow all instructions and answer the inbedded questions- and.pdf
please follow all instructions and answer the inbedded questions- and.pdfplease follow all instructions and answer the inbedded questions- and.pdf
please follow all instructions and answer the inbedded questions- and.pdfIan5L3Allanm
 
Written in C- requires linked lists- Please answer the 4 questions and.pdf
Written in C- requires linked lists- Please answer the 4 questions and.pdfWritten in C- requires linked lists- Please answer the 4 questions and.pdf
Written in C- requires linked lists- Please answer the 4 questions and.pdfsravi07
 
Written in C- requires linked lists- Please answer the 4 questions and (1).pdf
Written in C- requires linked lists- Please answer the 4 questions and (1).pdfWritten in C- requires linked lists- Please answer the 4 questions and (1).pdf
Written in C- requires linked lists- Please answer the 4 questions and (1).pdfsravi07
 
written in c- please answer the 4 questions and write the functions ba.pdf
written in c- please answer the 4 questions and write the functions ba.pdfwritten in c- please answer the 4 questions and write the functions ba.pdf
written in c- please answer the 4 questions and write the functions ba.pdfsravi07
 
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
 

Similaire à C++ detyrat postim_slideshare (20)

강의자료10
강의자료10강의자료10
강의자료10
 
강의자료7
강의자료7강의자료7
강의자료7
 
BackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdfBackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdf
 
Using the C++ programming language1. Implement the UnsortedList cl.pdf
Using the C++ programming language1. Implement the UnsortedList cl.pdfUsing the C++ programming language1. Implement the UnsortedList cl.pdf
Using the C++ programming language1. Implement the UnsortedList cl.pdf
 
This is the main file include itemh include itemList.pdf
This is the main file include itemh include itemList.pdfThis is the main file include itemh include itemList.pdf
This is the main file include itemh include itemList.pdf
 
Write a program to find the number of comparisons using the binary se.docx
 Write a program to find the number of comparisons using the binary se.docx Write a program to find the number of comparisons using the binary se.docx
Write a program to find the number of comparisons using the binary se.docx
 
Implement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdfImplement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdf
 
-- Reminder that your file name is incredibly important- Please do not.docx
-- Reminder that your file name is incredibly important- Please do not.docx-- Reminder that your file name is incredibly important- Please do not.docx
-- Reminder that your file name is incredibly important- Please do not.docx
 
강의자료9
강의자료9강의자료9
강의자료9
 
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
 
In C pls -- Write your name here -- Write the compiler used- Visual st.docx
In C pls -- Write your name here -- Write the compiler used- Visual st.docxIn C pls -- Write your name here -- Write the compiler used- Visual st.docx
In C pls -- Write your name here -- Write the compiler used- Visual st.docx
 
Pleae help me with this C++ question, ill upvote thanks.Write the .pdf
Pleae help me with this C++ question, ill upvote thanks.Write the .pdfPleae help me with this C++ question, ill upvote thanks.Write the .pdf
Pleae help me with this C++ question, ill upvote thanks.Write the .pdf
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfComplete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
 
please follow all instructions and answer the inbedded questions- and.pdf
please follow all instructions and answer the inbedded questions- and.pdfplease follow all instructions and answer the inbedded questions- and.pdf
please follow all instructions and answer the inbedded questions- and.pdf
 
Written in C- requires linked lists- Please answer the 4 questions and.pdf
Written in C- requires linked lists- Please answer the 4 questions and.pdfWritten in C- requires linked lists- Please answer the 4 questions and.pdf
Written in C- requires linked lists- Please answer the 4 questions and.pdf
 
Written in C- requires linked lists- Please answer the 4 questions and (1).pdf
Written in C- requires linked lists- Please answer the 4 questions and (1).pdfWritten in C- requires linked lists- Please answer the 4 questions and (1).pdf
Written in C- requires linked lists- Please answer the 4 questions and (1).pdf
 
written in c- please answer the 4 questions and write the functions ba.pdf
written in c- please answer the 4 questions and write the functions ba.pdfwritten in c- please answer the 4 questions and write the functions ba.pdf
written in c- please answer the 4 questions and write the functions ba.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
 
Java Generics
Java GenericsJava Generics
Java Generics
 

Plus de tctal

Prezantim Trajnime ne Tirane
Prezantim Trajnime ne TiranePrezantim Trajnime ne Tirane
Prezantim Trajnime ne Tiranetctal
 
Kurs LPIC1, Exam 101-500
Kurs LPIC1, Exam 101-500Kurs LPIC1, Exam 101-500
Kurs LPIC1, Exam 101-500tctal
 
Kurs Windows Server Administrator
Kurs Windows Server AdministratorKurs Windows Server Administrator
Kurs Windows Server Administratortctal
 
Kurs CCNA 200 - 301
Kurs CCNA 200 - 301Kurs CCNA 200 - 301
Kurs CCNA 200 - 301tctal
 
Kurs Arkitekture & Diagnostikim PC
Kurs Arkitekture & Diagnostikim PCKurs Arkitekture & Diagnostikim PC
Kurs Arkitekture & Diagnostikim PCtctal
 
Kurs Power BI
Kurs Power BI Kurs Power BI
Kurs Power BI tctal
 
Kurs Quality Assurance
Kurs Quality Assurance Kurs Quality Assurance
Kurs Quality Assurance tctal
 
Kurs Front End Development
Kurs Front End DevelopmentKurs Front End Development
Kurs Front End Developmenttctal
 
Kurs JavaScript Advance
Kurs JavaScript AdvanceKurs JavaScript Advance
Kurs JavaScript Advancetctal
 
Kurs C# .NET Web API
Kurs C# .NET Web API Kurs C# .NET Web API
Kurs C# .NET Web API tctal
 
React.JS Course
React.JS CourseReact.JS Course
React.JS Coursetctal
 
Kursi PHP fizikisht ne Tirane dhe online live
Kursi PHP fizikisht ne Tirane dhe online liveKursi PHP fizikisht ne Tirane dhe online live
Kursi PHP fizikisht ne Tirane dhe online livetctal
 
Kursi Front End Development
Kursi Front End DevelopmentKursi Front End Development
Kursi Front End Developmenttctal
 
Kursi Java Intermediate
Kursi Java IntermediateKursi Java Intermediate
Kursi Java Intermediatetctal
 
Kursi Java Basic
Kursi Java Basic Kursi Java Basic
Kursi Java Basic tctal
 
Kursi C++
Kursi C++Kursi C++
Kursi C++tctal
 
Kursi SPSS
Kursi SPSSKursi SPSS
Kursi SPSStctal
 
Kursi Python Basic
Kursi Python BasicKursi Python Basic
Kursi Python Basictctal
 
Kursi Microsoft Excel Intermediate
Kursi Microsoft Excel Intermediate Kursi Microsoft Excel Intermediate
Kursi Microsoft Excel Intermediate tctal
 
Kursi i programimit të Gjuhës R
Kursi i programimit të Gjuhës R Kursi i programimit të Gjuhës R
Kursi i programimit të Gjuhës R tctal
 

Plus de tctal (20)

Prezantim Trajnime ne Tirane
Prezantim Trajnime ne TiranePrezantim Trajnime ne Tirane
Prezantim Trajnime ne Tirane
 
Kurs LPIC1, Exam 101-500
Kurs LPIC1, Exam 101-500Kurs LPIC1, Exam 101-500
Kurs LPIC1, Exam 101-500
 
Kurs Windows Server Administrator
Kurs Windows Server AdministratorKurs Windows Server Administrator
Kurs Windows Server Administrator
 
Kurs CCNA 200 - 301
Kurs CCNA 200 - 301Kurs CCNA 200 - 301
Kurs CCNA 200 - 301
 
Kurs Arkitekture & Diagnostikim PC
Kurs Arkitekture & Diagnostikim PCKurs Arkitekture & Diagnostikim PC
Kurs Arkitekture & Diagnostikim PC
 
Kurs Power BI
Kurs Power BI Kurs Power BI
Kurs Power BI
 
Kurs Quality Assurance
Kurs Quality Assurance Kurs Quality Assurance
Kurs Quality Assurance
 
Kurs Front End Development
Kurs Front End DevelopmentKurs Front End Development
Kurs Front End Development
 
Kurs JavaScript Advance
Kurs JavaScript AdvanceKurs JavaScript Advance
Kurs JavaScript Advance
 
Kurs C# .NET Web API
Kurs C# .NET Web API Kurs C# .NET Web API
Kurs C# .NET Web API
 
React.JS Course
React.JS CourseReact.JS Course
React.JS Course
 
Kursi PHP fizikisht ne Tirane dhe online live
Kursi PHP fizikisht ne Tirane dhe online liveKursi PHP fizikisht ne Tirane dhe online live
Kursi PHP fizikisht ne Tirane dhe online live
 
Kursi Front End Development
Kursi Front End DevelopmentKursi Front End Development
Kursi Front End Development
 
Kursi Java Intermediate
Kursi Java IntermediateKursi Java Intermediate
Kursi Java Intermediate
 
Kursi Java Basic
Kursi Java Basic Kursi Java Basic
Kursi Java Basic
 
Kursi C++
Kursi C++Kursi C++
Kursi C++
 
Kursi SPSS
Kursi SPSSKursi SPSS
Kursi SPSS
 
Kursi Python Basic
Kursi Python BasicKursi Python Basic
Kursi Python Basic
 
Kursi Microsoft Excel Intermediate
Kursi Microsoft Excel Intermediate Kursi Microsoft Excel Intermediate
Kursi Microsoft Excel Intermediate
 
Kursi i programimit të Gjuhës R
Kursi i programimit të Gjuhës R Kursi i programimit të Gjuhës R
Kursi i programimit të Gjuhës R
 

Dernier

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 

Dernier (20)

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 

C++ detyrat postim_slideshare

  • 1. //driver.cpp //written to test doubly-linked list ADT //ItemType must have << and >> operators defined #include <fstream> #include <iostream> #include <string> #include "sortlist.h" using namespace std; template <class ItemType> void PrintAscending(ostream& dataFile, SortedType<ItemType>& list, string listName); //pre: list has been initialized // dataFile is open for output //post: each component in list has been written to dataFile // dataFile is still open template <class ItemType> void PrintDescending(ostream& dataFile, SortedType<ItemType>& list, string listName); //pre: list has been initialized // dataFile is open for output //post: each component in list has been written, in reverse order, to dataFile // dataFile is still open void DisplayMenu(int& choice); //pre: listA and listB have been initialized //post: displays a menu for list operations
  • 2. template <class ItemType> void Insert(SortedType<ItemType>& list, string listName); //pre: list has been initialized // item to insert is entered by the user in the function //post: Calls the ADT InsertItem and prints a message indicating // success or failure template <class ItemType> void Delete(SortedType<ItemType>& list, string listName); //pre: list has been initialized // item to delete is entered by the user within the function //post: Calls the ADT delete function and prints a message // indicating success or failure. template <class ItemType> void Retrieve(SortedType<ItemType> list); //pre: none //post: prompts user for item to retrieve from list; displays message // indicating whether or not item was found in the list int main() {
  • 3. SortedType<int> listA, listB, listC; int choice; while (true) { DisplayMenu(choice); switch (choice) { case 0: return 0; case 1: Insert(listA, "A"); break; case 2: Insert(listB, "B"); break; case 3: Delete(listA, "A"); break; case 4: listA.MakeEmpty(); break; case 5: Retrieve(listA); break; case 6: listC = listB = listA; break; case 7: listA.RemoveFirst(); break; case 8: listA.RemoveLast(); break;
  • 4. case 9: PrintAscending(cout, listA, "A"); PrintAscending(cout, listB, "B"); PrintAscending(cout, listC, "C"); break; case 10: PrintDescending(cout, listA, "A"); PrintDescending(cout, listB, "B"); PrintDescending(cout, listC, "C"); break; default: return 0; }//end switch }//end while }//end main template <class ItemType> void PrintAscending(ostream& dataFile, SortedType<ItemType>& list, string listName) { ItemType item; int length = list.LengthIs(); if (length == 0) {
  • 5. dataFile << "List " << listName << " is empty.n"; return; } dataFile << "List " << listName << " contains the following items:n"; list.ResetList(); for (int count=0; count<length; count++) { list.GetNextItem(item); dataFile << item; dataFile << " "; } dataFile << endl; } template <class ItemType> void PrintDescending(ostream& dataFile, SortedType<ItemType>& list, string listName) { ItemType item; int length = list.LengthIs(); if (length == 0) { dataFile << "List " << listName << " is empty.n"; return; } dataFile << "List " << listName << " contains the following items:n"; list.ResetListBackward();
  • 6. for (int count=0; count<length; count++) { list.GetPreviousItem(item); dataFile << item; dataFile << " "; } dataFile << endl; } void DisplayMenu(int& choice) { cout << "Please select from the menu.nn"; cout << "1tInsert an item to List A.n"; cout << "2tInsert an item to List B.n"; cout << "3tDelete an item from List A.n"; cout << "4tDelete all items from List A. (Make listA empty)n"; cout << "5tRetrieve an item from List A.n"; cout << "6tPerform assignment: listC = listB = listAn"; cout << "7tDelete first element of List A.n"; cout << "8tDelete last element of List A.n"; cout << "9tPrint lists in ascending order.n"; cout << "10tPrint lists in descending order.n"; cout << "0tExit programnn"; cin >> choice; } template <class ItemType>
  • 7. void Insert(SortedType<ItemType>& list, string listName) { ItemType item; cout << "Please enter the item to insert: "; cin >> item; if (list.InsertItem(item)) cout << item << " has been inserted into list " << listName << ".n"; else cout << "Unable to add " << item << " to " << listName << ".n"; } template <class ItemType> void Delete(SortedType<ItemType>& list, string listName) { ItemType item; cout << "Please enter the item to delete: "; cin >> item; if (list.DeleteItem(item)) cout << item << " has been deleted from list " << listName << ".n"; else cout << item << " was not in the list. List has not been changed.n"; } template <class ItemType> void Retrieve(SortedType<ItemType> list) {
  • 8. ItemType item; bool found; cout << "Please enter the item to be retrieved:n"; cin >> item; list.RetrieveItem(item, found); if (found) cout << item << " was in the list.n"; else cout << item << " was not in the list.n"; }
  • 9. // Implementation file for Sorted List ADT. // Class specification is in file sortlist.h. // Class is templated. template<class ItemType> struct NodeType { ItemType info; NodeType* next; NodeType* back; }; template <class ItemType> SortedType<ItemType>::SortedType () { length = 0; listData = NULL; listRear = NULL; } template <class ItemType> SortedType<ItemType>::~SortedType () { NodeType<ItemType>* tempPtr; while(listData != NULL) { tempPtr = listData; listData = listData->next; delete tempPtr; } }
  • 10. template <class ItemType> SortedType<ItemType>::SortedType(const SortedType& source) { //initialize variables length = 0; currentPos = NULL; listData = NULL; listRear = NULL; NodeType<ItemType>* sourcePtr; NodeType<ItemType>* newNodePtr; //copy nodes from rhs sourcePtr = source.listData; while (sourcePtr != NULL) { newNodePtr = new NodeType<ItemType>; newNodePtr->info = sourcePtr->info; if (listData == NULL) //first node to be copied { listData = newNodePtr; listRear = newNodePtr; newNodePtr->next = NULL; newNodePtr->back = NULL; } else { listRear->next = newNodePtr; newNodePtr->back = listRear; newNodePtr->next = NULL;
  • 11. listRear = newNodePtr; } length++; sourcePtr = sourcePtr->next; } } template <class ItemType> SortedType<ItemType> SortedType<ItemType>::operator =(const SortedType& rhs) { //check x=x case if (this == &rhs) return(*this); //delete existing list before assigning it the values in rtList NodeType<ItemType>* lhsPtr; NodeType<ItemType>* rhsPtr; while (listData != NULL) { lhsPtr = listData; listData = listData->next; delete lhsPtr; } length = 0; listRear = NULL; //copy nodes from rhs rhsPtr = rhs.listData; while (rhsPtr != NULL) { lhsPtr = new NodeType<ItemType>;
  • 12. lhsPtr->info = rhsPtr->info; if (listData == NULL) //first node to be copied { listData = lhsPtr; listRear = lhsPtr; lhsPtr->next = NULL; lhsPtr->back = NULL; } else { listRear->next = lhsPtr; lhsPtr->back = listRear; lhsPtr->next = NULL; listRear = lhsPtr; } length++; rhsPtr = rhsPtr->next; } return (*this); } template <class ItemType> bool SortedType<ItemType>::IsFull() const { NodeType<ItemType>* ptr; ptr = new NodeType<ItemType>; if (ptr == NULL) return true; else { delete ptr;
  • 13. return false; } } template <class ItemType> int SortedType<ItemType>::LengthIs() const { return length; } template <class ItemType> void SortedType<ItemType>::MakeEmpty() { NodeType<ItemType>* tempPtr; while (listData != NULL) { tempPtr = listData; listData = listData->next; delete tempPtr; } listRear = NULL; length = 0; } template <class ItemType> void SortedType<ItemType>::RetrieveItem(ItemType& item, bool& found) { bool moreToSearch; NodeType<ItemType>* location; location = listData;
  • 14. found = false; moreToSearch = (location != NULL); while (moreToSearch && !found) { if (location->info < item) { location = location->next; moreToSearch = (location != NULL); } else if (item == location->info) { found = true; item = location->info; } else moreToSearch = false; } } template <class ItemType> bool SortedType<ItemType>::InsertItem(ItemType item) { //modify the following code so that the function returns false //if item is already in the list //Prepare node for insertion NodeType<ItemType>* newNode; newNode = new NodeType<ItemType>; if (newNode == NULL) return false; newNode->info = item;
  • 15. //check if inserting into empty list if (listData == NULL) { newNode->next = NULL; newNode->back = NULL; listData = newNode; listRear = newNode; } else if(item ==listData->info) return false; //check if inserting before existing first item else if (item < listData->info) { newNode->next = listData; newNode->back = NULL; listData->back = newNode; listData = newNode; } //check if inserting after last item else if (item > listRear->info) { newNode->next = NULL; newNode->back = listRear; listRear->next = newNode; listRear = newNode; } else//inserting between existing nodes { // Find node that should precede newNode NodeType<ItemType>* location; location = listData; while (location->next->info < item) location = location->next;
  • 16. if(location->next->info == item) return false; else { //insert node into list. newNode->back = location; newNode->next = location->next; location->next->back = newNode; location->next = newNode; } } length++; return true; } template <class ItemType> void SortedType<ItemType>::RemoveFirst() { if(listData == NULL) return; NodeType<ItemType>* tempPtr = listData; if(listData->next == NULL) { delete tempPtr; listData = NULL; listRear = NULL; length = 0; } else { listData = listData->next; listData->back = NULL; delete tempPtr;
  • 17. length--; } } template <class ItemType> void SortedType<ItemType>::RemoveLast() { if(listData == NULL) return; NodeType<ItemType>* tempPtr = listRear; if(listData->next == NULL) { delete tempPtr; listData = NULL; listRear = NULL; length = 0; } else { listRear = listRear->back; listRear->next = NULL; delete tempPtr; length--; } } template <class ItemType> bool SortedType<ItemType>::DeleteItem(ItemType item) { if(listData == NULL) return false; NodeType<ItemType>* tempPtr = listData;
  • 18. if(item == listData->info) { if(listData->next == NULL) { delete tempPtr; listData = NULL; listRear = NULL; length = 0; } else { listData = listData->next; listData->back = NULL; delete tempPtr; length--; } } else if(item == listRear->info) { tempPtr =listRear; listRear =listRear->back; listRear->next = NULL; delete tempPtr; length--; } else { while(tempPtr->next->info != item) { if(tempPtr->next->info > item) return false; else tempPtr = tempPtr->next; }
  • 19. NodeType<ItemType>* newNode; newNode = tempPtr->next; tempPtr->next = newNode->next; newNode->next->back = tempPtr; delete newNode; length--; } return true; } template <class ItemType> void SortedType<ItemType>::ResetList() { currentPos = NULL; } template <class ItemType> void SortedType<ItemType>::ResetListBackward() { currentRev = NULL; } template <class ItemType> void SortedType<ItemType>::GetNextItem(ItemType& item) { if (currentPos == NULL) currentPos = listData; else currentPos = currentPos->next; item = currentPos->info; }
  • 20. template <class ItemType> void SortedType<ItemType>::GetPreviousItem(ItemType& item) { if (currentRev == NULL) currentRev = listRear; else currentRev = currentRev->back; item = currentRev->info; }
  • 21. // sortlist.h: Header file for Sorted List ADT. // Class is templated. // Assumption: ItemType is a type for which the comparison operators // are defined #ifndef SORTLIST_H #define SORTLIST_H template <class ItemType> struct NodeType; template <class ItemType> class SortedType { public: SortedType (); // Class constructor ~SortedType (); // Class destructor SortedType(const SortedType& source); //copy constructor SortedType operator =(const SortedType& rhs); //assignment operator bool IsFull() const; // Function: Determines whether list is full. // Post: Function value = (list is full)
  • 22. int LengthIs() const; // Function: Determines the number of elements in list. // Post: Function value = number of elements in list. void MakeEmpty(); // Function: Initializes list to empty state. // Post: List is empty. void RetrieveItem(ItemType& item, bool& found); // Function: Retrieves list element whose key matches item's key (if present). // Pre: Key member of item is initialized. // Post: If there is an element someItem whose key matches item's key, // then found = true and item is a copy of someItem; otherwise // found = false and item is unchanged. // List is unchanged. bool InsertItem(ItemType item); // Function: Adds item to list // Pre: List has been initialized // Post: Returns true if the item was successfully added // returns false if not able to add void RemoveFirst(); //pre: none //post: if list is not empty, first element has been removed, // else list is unchanged
  • 23. void RemoveLast(); //pre: none //post: if list is not empty, last element has been removed, // else list is unchanged bool DeleteItem(ItemType item); // Function: Deletes the element whose key matches item's key. // Pre: Key member of item is initialized. // At most one element in list has a key matching item's key. // Post: No element in list has a key matching item's key. void ResetList(); // Function: Initializes current position for an iteration through the list. // Pre: List has been initialized // Post: Current position is prior to first element of list. void GetNextItem(ItemType&); // Function: Gets the next element in list. // Pre: Current position is defined. // Element at current position is not last in list. // Post: Current position is updated to next position. // item is a copy of element at current position. void ResetListBackward();
  • 24. // Function: Initializes current position for a backward iteration through the list. // Pre: List has been initialized // Post: Current position is after the last element of the list void GetPreviousItem(ItemType&); // Function: Gets the previous element in list. // Pre: Current position is defined. // Element at current position is not first in list. // Post: Current position is updated to previous position. // item is a copy of element at current position. private: int length; NodeType<ItemType>* listData; NodeType<ItemType>* listRear; NodeType<ItemType>* currentPos; //for forward traversal NodeType<ItemType>* currentRev; //for backward traversal }; #include "sortlist.cpp" #endif