Minggu, 18 April 2010

Doubly Linked List dengan C++

Bedanya doubly linked list dengan singly linked list yaitu setiap node pada doubly linked memiliki pointer yang menunjuk ke node sebelumnya. Berbeda dengan singly linked list yang hanya punya pointer yang menuju ke node setelahnya. Berikut source code class doubly linked list.

//--------------------------------------------------------//


#include "iostream"

using namespace std;

class linkedlist
{
private:
struct node
{
int data;
node *next, *prev;
} *head, *tail;
public:
linkedlist();
bool isempty();
void addfirst(int data);
void addlast(int data);
void addafter(int data, int index);
void delfirst();
void dellast();
void del(int index);
int get(int index);
~linkedlist();
};

//Implementasi fungsi-fungsi dalam class:

#include "linkedlist.h"

linkedlist::linkedlist()
{
head = tail = NULL;
}

bool linkedlist::isempty()
{
return head == NULL;
}

void linkedlist::addfirst(int data)
{
node *baru = new node;
baru->data = data;
if(isempty())
{
head = tail = baru;
baru->next = baru->prev = NULL;
}
else
{
baru->next = head;
baru->prev = NULL;
head->prev = baru;
head = baru;
}
}

void linkedlist::addlast(int data)
{
node *baru = new node;
baru->data = data;
if(isempty())
{
head = tail = baru;
baru->next = baru->prev = NULL;
}
else
{
baru->prev = tail;
baru->next = NULL;
tail->next = baru;
tail = baru;
}
}

void linkedlist::addafter(int data, int index)
{
node *baru = new node, *temp = head;
baru->data = data;
for(int i = 0; i < index - 1 && temp->next != NULL; i++)
temp = temp->next;
baru->next = temp->next;
baru->prev = temp;
temp->next->prev = baru;
temp->next = baru;
}

void linkedlist::delfirst()
{
if(isempty()) return;
else if(head == tail)
{
head = NULL;
delete head;
return;
}
else
{
node *temp = head;
head = temp->next;
head->prev = NULL;
delete temp;
}
}

void linkedlist::dellast()
{
if(isempty()) return;
else if(head == tail)
{
delete head;
return;
}
else
{
node *temp = tail;
tail = temp->prev;
tail->next = NULL;
delete temp;
}
}

void linkedlist::del(int index)
{
if(isempty()) return;
node *temp = head;
for(int i = 0; i < index - 1 && temp->next != NULL; i++)
temp = temp->next;
node *temp2 = temp->prev;
temp2->next = temp->next;
temp->next->prev = temp2;
temp = NULL;
delete temp;
}

int linkedlist::get(int index)
{
if(isempty()) return -1;
node *temp = head;
for(int i = 0; i < index - 1 && temp->next != NULL; i++)
temp = temp->next;
return temp->data;
}

linkedlist::~linkedlist()
{
node *q;
q = head;
if(head == NULL) return;
while(q != NULL)
{
q = head->next;
delete head;
head = q;
}
}

//--------------------------------------------------------//


1 komentar: