I have to return the head and tail of the list in GetHead() and GetTail().
I tried to return head and tail by themselves and get the error: cannot initialize return object of type 'int' with an lvalue of type 'Node *const' return tail;
I also tried to return head->value and tail->value and it gives me EXC_BAD_ACCESS in string() const.
template<typename T>
class Node
{
private:
T value;
Node* prev;
Node* next;
public:
Node(T value, Node* prev = NULL, Node* next = NULL);
friend class List<T>;
};
template<typename T>
class List
{
private:
Node<T>* head;
Node<T>* tail;
public:
List();
List(const List<T>& src);
~List();
bool IsEmpty() const;
T GetHead() const;
T GetTail() const;
void AddToHead(T v);
void AddToTail(T v);
bool RemoveHead();
bool RemoveTail();
operator string() const;
///////////////////////////////////////////
// Do not change the above prototype.
// Add member function(s) below if you need.
// Do not change the below.
///////////////////////////////////////////
};
template<typename T>
Node<T>::Node(T value, Node* prev, Node* next)
{
this->value = value;
this->prev = prev;
this->next = next;
}
template<typename T>
List<T>::operator string() const
{
if (IsEmpty())
return "()";
stringstream os;
os << "(";
Node<T>* r = head;
while (r != tail)
{
os << r->value << ",";
r = r->next;
}
os << r->value << ")";
string str = os.str();
return str;
}
template<typename T>
List<T>::List()
{
// make list empty
head = tail = NULL;
}
template<typename T>
List<T>::List(const List<T>& src)
{
// make list empty
head = tail = NULL;
// copy all contents in src into this
Node<T>* node = src.head;
while(node != NULL)
{
AddToTail(node->value);
node = node->next;
}
}
template<typename T>
bool List<T>::IsEmpty() const
{
return (head == NULL);
}
///////////////////////////////////////////
// Do not change the above.
// Implement your own member functions below.
template<typename T>
List<T>::~List()
{
while (!IsEmpty())
RemoveTail();
}
template<typename T>
void List<T>::AddToTail(T v)
{
if (IsEmpty())
head = tail = new Node<T>(v, NULL, NULL);
else
{
head = new Node<T>(v, tail, NULL);
head->prev->next = tail;
}
}
template<typename T>
void List<T>::AddToHead(T v)
{
if (IsEmpty())
head = tail = new Node<T>(v, NULL, NULL);
else
{
head = new Node<T>(v, NULL, head);
head->next->prev = head;
}
}
template<typename T>
bool List<T>::RemoveHead()
{
if(IsEmpty())
return false;
if(head == tail)
{
delete tail;
head = tail = NULL;
return true;
}
else
{
head = head->next;
delete head->prev;
head->prev = NULL;
return true;
}
}
template<typename T>
bool List<T>::RemoveTail()
{
if(IsEmpty())
return false;
if(head == tail)
{
delete tail;
head = tail = NULL;
return true;
}
else
{
tail = tail->prev;
delete tail->next;
tail->next = NULL;
return true;
}
}
template<typename T>
T List<T>::GetHead() const
{
return head;
}
template<typename T>
T List<T>::GetTail() const
{
return tail;
}```
Aucun commentaire:
Enregistrer un commentaire