akevintg

TM Double Link List

Mar 20th, 2014
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<Windows.h>
  3.  
  4. struct data{
  5.     int angka;
  6.     struct data *prev;
  7.     struct data *next;
  8. }*head,*now,*temp,*tail;
  9.  
  10. void ins(int x){
  11.     now=head;
  12.     for(now=head;now!=NULL;now=now->next){
  13.         if(x>now->angka){
  14.             temp=now;
  15.             now=(struct data*)malloc(sizeof(data));
  16.             now->angka=x;
  17.             now->next=temp;
  18.             now->prev=temp->prev;
  19.             temp->prev=now;
  20.             if(now->prev!=NULL){
  21.                 now=now->prev;
  22.                 now->next=temp->prev;
  23.             }//kalo dia head
  24.             else
  25.                 head=now;
  26.             break;
  27.         }
  28.         else if (now->next==NULL){//kalo tail
  29.             temp=now;
  30.             now=(struct data*)malloc(sizeof(data));
  31.             now->angka=x;
  32.             now->prev=temp;
  33.             now->next=0;
  34.             tail=now;
  35.             temp->next=now;
  36.             break;
  37.         }
  38.     }
  39. }
  40.  
  41. void intz(int x){
  42.     now=(struct data*)malloc(sizeof(data));
  43.     if(head==0)//data perdana
  44.         tail=now;
  45.     now->angka=x;
  46.     now->next=head;//Double Link list Start
  47.     head=now;
  48.     now->prev=NULL;
  49.     if(now->next!=0){
  50.         temp=now;
  51.         now=now->next;
  52.         now->prev=temp;
  53.     }// Double Link list end
  54. }
  55.  
  56. void cetak(){
  57.     for(now=tail;now!=NULL;now=now->prev){
  58.         printf("%d",now->angka);
  59.         if (now->prev!=NULL)
  60.             printf(" -> ");
  61.     }
  62.     printf("\n");
  63. }
  64.  
  65. int main(){
  66.    
  67.     head=0;
  68.     temp=0;
  69.     printf("Sebelum insert\n");
  70.     intz(1);
  71.     intz(3);
  72.     cetak();
  73.     printf("Setelah insert awal\n");
  74.     ins(5);
  75.     cetak();
  76.     printf("Setelah insert akhir\n");
  77.     ins(0);
  78.     cetak();
  79.     printf("Setelah insert tengah\n");
  80.     ins(2);
  81.     cetak();
  82.     now=head;
  83.     getchar();
  84. }
Advertisement
Add Comment
Please, Sign In to add comment