You are on page 1of 3

Cahyo Dimas Kurnianto FTI-UKSW

Linked List
1. Linked list adalah perintah atau struktur yang digunakan untuk pemberian data dalam jumlah yang besar dan biasanya dikombinasikan dengan perintah struct, dimana linked list lebih dinamis daripada struktur array. Dari pada array, linked list juga dapat memaksimalkan penggunaan memory tanpa terjadi pemborosan memory. Fungsi dalam linked list : malloc() : fungsi ini digunakan untuk alokasi/peyimpanan memory secara dinamis yang tersimpan pada header <stdlib.h> free() : fungsi ini digunakan untuk membebaskan memory yang sebelumnya disimpan pada fungsi malloc() yang tersimpan pada header <stdlib.h> Jenis linked list : Singly linked list Contoh : #include <stdio.h> #include <stdlib.h> void main() { struct linked { int x; struct linked *next; }; struct linked *head=NULL,*first=NULL,*second= NULL; for (int i=0; i<5; i++) { second = (struct linked *)malloc (sizeof(struct linked)); second -> x = i; if (head == NULL) { head = second; first = second; } else { first -> next = second; first = second; } } first -> next = NULL; first = head; while (first != NULL) { printf("%d ", first -> x); first = first -> next; } printf("\n"); }

Samidfti.blogspot.com

Cahyo Dimas Kurnianto FTI-UKSW

Doubly linked list Contoh : #include <stdio.h> #include <stdlib.h> second; void main() { struct linked { int x; struct linked *prev; struct linked *next; }; struct linked *head=NULL,*first=NULL,*second= NULL,*third=NULL; for (int i=0;i<5;i++) { second = (struct linked *)malloc (sizeof(struct linked)); second -> x = i; if (head == NULL) { head = second; head -> prev = NULL; first = second; } else

{ first -> next = second -> prev = first; first = second; } } first -> next = NULL; third = first; first = head; do { printf("%d ", first -> x); first = first -> next; } while (first != NULL); printf("\n"); first = third; do { printf("%d ", first -> x); first = first -> prev; } while (first != NULL); }

2. Contoh program #include <stdio.h> //mengaktifkan perintah printf #include <stdlib.h> //mengaktifkan perintah malloc dan free void main() { struct node { int a; int b; Samidfti.blogspot.com

/*perintah struct bernama node yang berisi 2 variabel yaitu a dan b*/

Cahyo Dimas Kurnianto FTI-UKSW

}; struct node * x = (struct node*)malloc(sizeof (struct node)); /*perintah dasar dalam linked list, dimana malloc(sizeof(struct node)) berfungsi untuk mengalokasikan memory sebanyak yang ada pada struct node*/ printf("Angka pertama : ");scanf("%d",&x->a); printf("Angka kedua : ");scanf("\n%d",&x->b); //inputkan data

printf("\nAngka yang diinputkan adalah %d%d",x->a,x->b); kemudian akan dicetak free(x); }

//data yang diinputkan

//mendelokasikan memory yang sebelumnya disimpan pada fungsi malloc

Samidfti.blogspot.com

You might also like