#include "LinkedList.h"
using namespace std;
namespace hong_lab5
{
//create empty linkedlist
LinkedList::LinkedList()
{
head_ptr = NULL;
tail_ptr = NULL;
current_ptr = NULL;
list_length=0;
}
//create a linked list with data
LinkedList::LinkedList(data_type& data)
{
head_ptr = new node(data);
tail_ptr = head_ptr;
current_ptr = tail_ptr;
list_length=1;
}
//destructor
LinkedList::~LinkedList()
{
while(head_ptr != NULL)
remove_from_head();
tail_ptr = NULL;
}
void LinkedList::add_to_head(data_type& data)
{
//add node for empty list
if(list_length==0)
{
head_ptr = new node(data);
tail_ptr = head_ptr;
current_ptr = tail_ptr;
list_length=1;
}
//insert node at head
else
{
node* head_insert = new node(data); // new node on the heap
head_ptr -> set_previous(head_insert); //set the heads "previous" ptr to the new head and set the next nodes "next"
//ptr to the node at the current head
head_insert->set_next(head_ptr);
head_ptr = head_insert; // set the head ptr from the list to the new node
list_length++; // increment to the list
head_insert = NULL;
}
}
void LinkedList::add_to_tail(data_type& data)
{
if(list_length==0)
{
head_ptr = new node(data); // add node for empty list
tail_ptr = head_ptr;
list_length=1;
}
else // insert node at tail
{
node* tail_insert = new node(data); // new node on the heap
tail_ptr ->set_next(tail_insert);
tail_insert->set_previous(tail_ptr);
tail_ptr = tail_insert;
list_length++;
tail_insert = NULL;
}
}
void LinkedList::remove_from_head()//do nothing for empty list
{
if(list_length==0)
return;
else if(list_length==1)
{
delete head_ptr;
head_ptr = NULL;
tail_ptr = NULL;
list_length--;
return;
}
else
{
node* temp_head_ptr = head_ptr;
head_ptr = temp_head_ptr->get_next();
delete temp_head_ptr;
list_length--;
temp_head_ptr=NULL;
}
}
void LinkedList::remove_from_tail()
{
if(list_length==0)
return;
else if(list_length==1)
{
delete head_ptr;
head_ptr=NULL;
tail_ptr=NULL;
list_length--;
return;
}
else
{
node* temp_tail_ptr = tail_ptr;
tail_ptr = temp_tail_ptr->get_previous();
delete temp_tail_ptr;
list_length--;
temp_tail_ptr=NULL;
}
}
void LinkedList::forward()
{
current_ptr = current_ptr ->get_next();
}
void LinkedList::back()
{
current_ptr = current_ptr ->get_previous();
}
void LinkedList::move_to_head()
{
current_ptr = head_ptr;
}
void LinkedList::move_to_tail()
{
current_ptr = tail_ptr;
}
LinkedList::data_type LinkedList::get_current() const
{
return current_ptr->get_data();
}
std::size_t LinkedList::size()
{
return list_length;
}
}
评论0