Berikut ini source code class linked list buatan saya.. B-)
Di sini tipe data yang digunakan adalah integer. Tipe data bisa diganti sesuai kebutuhan.
//--------------------------------------------------------//
#include "iostream"
using namespace std;
class linkedlist
{
private:
struct node
{
int data;
node *next;
} *head, *tail;
public:
linkedlist(); //constructor
bool isempty(); //cek kosongnya list
void addfirst(int data); //menambah data pada list dari awal
void addlast(int data); //menambah data pada list dari belakang
void addafter(int data, int index); //menambah data pada list setelah indeks yang ditentukan
void delfirst(); //menghapus data awal dari list
void dellast(); //menghapus data akhir dari list
void deletion(int index); //menghapus data indeks ke-n dari list
int get(int index); //mengambil data index ke-n tanpa menghapusnya
~linkedlist(); //destructor
};
//Implementasi fungsi-fungsi dalam class:
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 = NULL;
}
else
{
baru->next = head;
head = baru;
}
}
void linkedlist::addlast(int data)
{
node *baru = new node;
baru->data = data;
if(isempty())
{
head = tail = baru;
baru->next = NULL;
}
else
{
tail->next = baru;
tail = baru;
tail->next = NULL;
}
}
void linkedlist::addafter(int data, int index)
{
node *baru = new node, *temp = head;
baru->data = data;
for(int i = 0; i <>next != NULL; i++)
temp = temp->next;
baru->next = temp->next;
temp->next = baru;
}
void linkedlist::delfirst()
{
node *temp = head;
if(isempty()) return;
else
{
head = temp->next;
temp = NULL;
delete temp;
}
}
void linkedlist::dellast()
{
node *temp = head;
if(isempty()) return;
else if(head == tail)
{
delete head;
return;
}
for(int i = 0; temp->next->next != NULL; i++)
temp = temp->next;
tail = temp;
temp->next = NULL;
delete temp->next;
}
void linkedlist::deletion(int index)
{
node *temp = head, *temp2;
if(isempty()) return;
for(int i = 0; i <>next != NULL; i++)
temp = temp->next;
temp2 = temp->next;
temp->next = temp->next->next;
temp2 = NULL;
delete temp2;
}
int linkedlist::get(int index)
{
node *temp = head;
if(isempty()) return -1;
for(int i = 0; i <>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;
}
}
//--------------------------------------------------------//
Minggu, 18 April 2010
Singly Linked List dengan C++
Langganan:
Posting Komentar (Atom)
nice post..
BalasHapusThanks..