Work on SingleList, makeEmpty

This commit is contained in:
Shaun Reed 2020-04-19 22:37:05 -04:00
parent a2c326c177
commit 56d87bfb8a
3 changed files with 33 additions and 19 deletions

View File

@ -23,17 +23,15 @@ int main()
bool exit = false;
int choice = -1;
int val, key;
SingleList test2;
while (!exit)
{
test2 = testList;
std::cout << "##### Singly Linked List Menu #####\n\t0. Exit"
<< "\n\t1. Insert\n\t2. Insert at\n\t3. Empty list\n\t4. Peek top of list"
<< "\n\t5. Print list\n\t6. Find\n\t7. Remove\n\t8. Replace\n";
std::cin >> choice;
std::cin.clear();
switch (choice)
{
switch (choice) {
case EXIT:
exit = true;
break;
@ -69,8 +67,6 @@ int main()
case PRINT:
testList.print();
test2.print();
// test3.print();
break;
case FIND:

View File

@ -19,21 +19,34 @@
*
* @param rhs SingleList object
*/
SingleList::SingleList(const SingleList& rhs) : head (rhs.head)
SingleList::SingleList(const SingleList& rhs)
{
Node *cp = rhs.head;
Node *tempHead;
if (cp == NULL) head = NULL;
else {
head = new Node(cp->data);
tempHead = head;
while (cp->next != NULL) {
cp = cp->next;
head->next = new Node(cp->data);
head = head->next;
}
head = tempHead;
}
}
/**
* @brief Copy the rhs SingleList::SingleList into the lhs of an assignemnt
* @brief Shallow copy of the rhs into the lhs of the assignemnt
*
* @param rhs SingleList object
* @return SingleList& The copied rhs SingleList to the lhs of the assignment
* @return SingleList& A shallow copy of the rhs SingleList in the assignment
*/
SingleList SingleList::operator=(SingleList rhs)
SingleList SingleList::operator=(SingleList& rhs)
{
if (this == &rhs) return *this;
std::swap(head, rhs.head);
// head = rhs.head;
else head = rhs.head;
return *this;
}
@ -117,10 +130,15 @@ bool SingleList::replace(int val, int key)
*/
void SingleList::makeEmpty()
{
Node *temp(head);
while(!isEmpty()) {
head = head->next;
Node *nextNode = head->next;
Node *temp;
delete head;
head = NULL;
while(nextNode != NULL) {
temp = nextNode;
nextNode = nextNode->next;
delete temp;
temp = NULL;
}
}

View File

@ -6,11 +6,11 @@
## Structure: Remove: Insert: Insert at: Replace: ##
## o-o-o-o-o-o o-o--x-->o-o-o o o o ##
## | /| / \ ##
## o-o~o-o-o-o o-o~o-o-o-o o-o~x~o-o-o ##
## o-o-o-o-o-o o-o~o-o-o-o o-o~x~o-o-o ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com | GitHub: shaunrd0 ##
##############################################################################
## singlelist.cpp
## singlelist.h
*/
#ifndef LINKEDLIST_H
@ -22,7 +22,7 @@ class SingleList{
public:
SingleList() : head(NULL) {};
SingleList(const SingleList& rhs);
SingleList operator=(SingleList rhs);
SingleList operator=(SingleList& rhs);
~SingleList();
bool insert(int val);
bool insert(int val, int key);
@ -38,7 +38,7 @@ class SingleList{
struct Node {
int data;
Node *next;
Node(): data(00), next(NULL) {};
Node(): data(), next(NULL) {};
Node(int val): data(val), next(NULL) {};
};
Node *head;