Unsorted Linked List
Unsorted Linked List
Example:
#include <iostream>
using namespace std;
template<class ItemType>
struct NodeType {
ItemType info;
NodeType<ItemType>* next;
};
template<class ItemType>
class UnsortedType {
public:
UnsortedType(); // Constructor
~UnsortedType(); // Destructor
void MakeEmpty();
bool IsFull() const;
int LengthIs() const;
void RetrieveItem(ItemType& item, bool& found);
void InsertItem(ItemType item);
void DeleteItem(ItemType item);
void ResetList();
bool IsLastItem() const;
void GetNextItem(ItemType& item);
private:
int length;
NodeType<ItemType>* listData;
NodeType<ItemType>* currentPos;
};
// Constructor
template<class ItemType>
UnsortedType<ItemType>::UnsortedType() {
length = 0;
listData = NULL;
}
// Destructor
template<class ItemType>
UnsortedType<ItemType>::~UnsortedType() {
MakeEmpty();
}
if (item == listData->info) {
tempLocation = location;
listData = listData->next; // delete the first node
} else {
while (!(item == (location->next)->info)) {
location = location->next;
}
tempLocation = location->next; // node to be deleted
location->next = (location->next)->next;
}
delete tempLocation;
length--;
}
int main() {
UnsortedType<int> list;
// Retrieve an item
int item = 3;
bool found;
list.RetrieveItem(item, found);
if (found) {
cout << "Item " << item << " found in the list." << endl;
} else {
cout << "Item " << item << " not found in the list." << endl;
}
// Delete an item
list.DeleteItem(5);
return 0;
}
Exercise1: Write a client function that merges two instances of the Unsorted List
ADT using the following specification.
template<class ItemType>
MergeLists(UnsortedType<ItemType> list1,
UnsortedType<ItemType> list2,
UnsortedType<ItemType>& result)
Function: Merges two unsorted lists into a third unsorted
list (no duplicates).
Preconditions: list1 and list2 have been initialized.
Postconditions: result is an unsorted list that contains all
of the items from list1 and list2
Solution: