#include <cstdlib>
#include <cstdio>
#include <iostream>
using namespace std;
#include "CardLinkedList.h"
CardLinkedList::CardLinkedList()
{
head = NULL;
tail = NULL;
}
CardLinkedList::~CardLinkedList()
{
CardNode* current = head;
while (current != NULL)
{
CardNode* next = current->getNext();
delete current;
current = next;
}
head = NULL;
tail = NULL;
}
/* addHead
* add an item to the front of the linked list
*/
void CardLinkedList::addHead(Card* c)
{
CardNode *l = new CardNode(c);
if (head == NULL)
{
head = l;
tail = l;
}
else
{
l->setNext(head);
head = l;
for (tail= l ; tail->getNext() != NULL ; tail->getNext())
tail = tail->getNext();
}
}
/* addTail
* Add an item to the end (tail) of the list
*/
void CardLinkedList::addTail(Card* c)
{
CardNode *l = new CardNode(c);
if (head == NULL)
{
head = l;
tail = l;
}
else
{
CardNode *l2;
for(l2 = head;l2->getNext() != NULL; l2 = l2->getNext());
l2->setNext(l);
tail = l2->getNext();
}
}
/* removeHead
* Removes the item at the head of the list
*/
bool CardLinkedList::removeHead()
{
// if the list is empty, return 0
if (head == NULL)
return false;
if (head->getNext() == NULL)
{
delete head;
head = NULL;
tail = NULL;
return true;
}
// set a temporary pointer to head
CardNode *tmp = head;
// advance head so it points to the next one
head = head->getNext();
// delete the IntNode
delete tmp;
// return the value
return true;
}
/* removeTail
* removes the last (tail) item from a linked list
* Returns true if it removed something, false if the list was empty
*/
bool CardLinkedList::removeTail()
{
CardNode* tmp = head;
if (head == NULL)
return false;
if (head->getNext()==NULL)
{
delete head;
head = NULL;
tail = NULL;
return true;
}
while (tmp->getNext() != tail)
tmp = tmp->getNext();
delete tail;
tmp->setNext(NULL);
tail = tmp;
return true;
}
/* peekHead
* return the item at the head of the list
* If the list is empty, return 0
*/
Card* CardLinkedList::peekHead()
{
CardNode* current = head;
if (current != NULL)
return current->getValue();
else
return 0;
}
/* peekTail
* return the item at the end (tail) of the list
* If the list is empty, return 0
* TODO: Implement this function. Make sure you take advantage of the tail ptr
*/
Card* CardLinkedList::peekTail()
{
CardNode* current = head;
if (current == NULL)
return 0;
else
return tail->getValue();
}
/* printList
*
* print all of the items in the linked list
*/
void CardLinkedList::printList()
{
CardNode *l;
printf("List: ");
for(l = head; l != NULL; l = l->getNext())
{
l->printCardNode();
printf(", ");
}
printf("\n");
/* Your print method printList has the following key features,
* some of which may need adjustment:
* tmp->printIntNode(); in its loop
* printf(", "); in its loop
* After the loop, printf("\n");
*/
}
void CardLinkedList::addSorted(Card *c)
{
}