C++ ssd5 11 optional exercise1

#ifndef _ENHANCEDLINKEDLIST_H_
#define _ENHANCEDLINKEDLIST_H_

#include "LinkedList.h"

using namespace std;


class ListItemNotFoundException : public logic_error
{
public:
ListItemNotFoundException(const string& e) throw() :
logic_error("Empty List or Item Not Found Exception" + e) {}
};

template <typename T>
class EnhancedLinkedList : public LinkedList<T>
{
public:
EnhancedLinkedList() :LinkedList() {}
T& find_first(const T& key);
EnhancedLinkedList find_all(const T& key);
void remove_first(const T& key);
void remove_all(const T& key);

};

template <typename T>
T& EnhancedLinkedList<T>::find_first(const T& key)
{
Node<T>* current = this->head;//get the head point
if (this->empty())
throw ListItemNotFoundException("empty list!");//if list is empty
while (current != NULL)//search
{

if (current->getData() == key)
return current->getData();
else
current = current->getNext();
}
if (current == NULL)
throw ListItemNotFoundException("not found this element!");//if not found

}

template <typename T>
EnhancedLinkedList<T> EnhancedLinkedList<T>::find_all(const T& key)
{
EnhancedLinkedList list;//new list
Node<T>* current = this->head;//get the LinkedList head

while (current != NULL)
{
if (current->getData() == key)
{
list.push_back(current->getData());//insert one data
/*list.head = current;
Node<T>* now_current = list.head;
now_current->getData() = current->getData;*/
}

current = current->getNext();
}

return list;

}

template <typename T>
void EnhancedLinkedList<T>::remove_first(const T& key)
{
Node<T>* current;
//如果是空表
if (head == NULL)
return;
//如果头节点是key
else if (head->getData() == key)
{
Node<T>* del;
del = head;
head = head->getNext();//重新拉链
delete del;
this->count--;
return;
}
else
{
current = head;//定义当前指针
Node<T>* before = head;
while (current != NULL)
{
if (current->getData() == key)
{

Node<T>* del = current;
current = current->getNext();//重新拉链
before->getNext() = current;//这里一开始忘记了,在这种情况下要改变两个指针
delete del;
this->count--;
return;
}
else
before = current;
current = current->getNext();//如果不是,循环执行
}

}
return ;
}


template <typename T>
void EnhancedLinkedList<T>::remove_all(const T& key)
{
//如果头节点是空
if (head == NULL)
return;
//如果头节点是key
else if (head->getData() == key)
{
Node<T>* del = head;
head = head->getNext();//重新拉链
delete del;
this->count--;
}

Node<T>* current = head;
Node<T>* before = head;
while (current != NULL)
{
if (current->getData() == key)
{
Node<T>* del = current;
current = current->getNext();//重新拉链
before->getNext() = current;
delete del;
count--;
}
else
{
before = current;
current = current->getNext();
}
}

}

 

#endif

posted @ 2016-03-29 13:26  BigMinnow  阅读(175)  评论(0编辑  收藏  举报