Struktur Data – Doubly Linked List
#include <stdio.h> #include <stdlib.h> struct data{ int angka; struct data *prev; struct data *next; }*head,*now,*temp,*tail; void ins(int x){ now=head; for(now=head;now!=NULL;now=now->next){ if(x>now->angka){ temp=now; now=(struct data*)malloc(sizeof(data)); now->angka=x; now->next=temp; now->prev=temp->prev; temp->prev=now; if(now->prev!=NULL){ now=now->prev; now->next=temp->prev; }//kalau head else head=now; break; } else if (now->next==NULL){//kalau tail temp=now; now=(struct data*)malloc(sizeof(data)); now->angka=x; now->prev=temp; now->next=0; tail=now; temp->next=now; break; } } } void intz(int x){ now=(struct data*)malloc(sizeof(data)); if(head==0)//data perdana tail=now; now->angka=x; now->next=head;//Double Link list Start head=now; now->prev=NULL; if(now->next!=0){ temp=now; now=now->next; now->prev=temp; }// Double Link list end } void cetak(){ for(now=tail;now!=NULL;now=now->prev){ printf("%d",now->angka); if (now->prev!=NULL) printf(" -> "); } printf("\n"); } int main(){ printf("Nama : Kenneth\n"); printf("NIM : 1701290425\n"); printf("Kelas : 32PPT\n"); printf("Double Linked List\n\n"); head=0; temp=0; printf("Sebelum insert\n"); intz(1); intz(3); cetak(); printf("\nSetelah insert tengah\n"); ins(2); cetak(); printf("\nSetelah insert awal\n"); ins(0); cetak(); printf("\nSetelah insert akhir\n"); ins(5); cetak(); now=head; getchar(); }
No Comments »
RSS feed for comments on this post. TrackBack URL