Linked List biasa kita gunakan untuk mempermudah insertion data pada database..Serta tidak membuang-buang memory, karena menggunakan malloc yang disebut juga memory allocation sesuai dengan memory yang dibutuhkan.
Seperti apa sih penggunaan Linked List itu ?
berikut ini adalah contoh kodingan milik saya :
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
node *next;
} *head, *tail, *curr;
struct node *create(int key) {
struct node *newnode = (struct node*)malloc(sizeof(struct node));
newnode->key = key;
newnode->next = NULL;
return newnode;
};
void pushHead(int key) {
node *temp = create(key);
if(!head) {
head = tail = temp;
}else {
temp->next = head;
head = temp;
}
}
void pushTail(int key) {
node *temp = create(key);
if(!head) {
head=tail=temp;
}else{
tail->next = temp;
tail = temp;
}
}
void pushMid(int key) {
node *temp = create(key);
if(!head) {
head = tail = temp;
} else if (head->key > temp->key){
pushHead(key);
} else if (tail->key < temp->key) {
pushTail(key);
} else {
curr = head;
while(curr) {
if(curr->key > temp->key) {
temp->next = curr;
}
}
}
}
void popHead() {
if(head==tail) {
free(head);
} else {
node *temp = head->next;
head->next = NULL;
free(head);
head = temp;
}
}
void popTail(){
if(!head) return;
if(head==tail){
free(head);
head = tail = NULL;
return;
}
curr = head;
while(curr->next!=tail){
curr = curr->next;
}
tail = curr;
free(curr->next);
tail->next = NULL;
}
void popSearch(int key){
if(!head) return;
if(head==tail){
free(head);
head = tail = NULL;
return;
}
if(head->key == key) popHead();
else if(tail->key == key) popTail();
else{
curr = head;
while(curr->next){
if(curr->next->key == key){
node *temp = curr->next;
curr->next = curr->next->next;
free(temp);
break;
}
curr = curr->next;
}
}
}
void popMid(int index){
if(!head) return;
if(head==tail){
free(head);
head = tail = NULL;
return;
}
if(index==0) popHead();
else{
curr = head;
for(int i=0; i<index-1; i++){
curr = curr->next;
if(!curr) break;
}
if(!curr || !curr->next) printf("Error! PopMid at index %d failed!\n", index);
else{
node *temp = curr->next;
curr->next = temp->next;
free(temp);
}
}
}
void printall() {
curr = head;
while (curr != NULL) {
printf ("%d ", curr->key);
curr = curr->next;
}
puts("");
}
int main() {
pushTail (5);
printall();
pushTail (10);
printall();
pushHead (15);
printall();
return 0;
}
Kodingan dasar untuk single linked list akan seperti ini.
Jangan lupa untuk menggunakan library stdlib yaa...
karena ada penggunaan malloc..
selain stdlib bisa juga menggunakan library malloc
yaitu : #include<malloc.h>
Push adalah function untuk insertion data
Pop adalah function untuk deletion data
Printall adalah function untuk view data
dan inilah hasil output yang dikeluarkan dari kodingan diatas...
jika ada pertanyaan silahkan comment...
Selamat berkoding :)

Tidak ada komentar:
Posting Komentar