mbah_bejo

Linked List Sorted

Mar 3rd, 2020
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.31 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node
  5. {
  6.     int num;
  7.     struct node *next;
  8.    
  9. }*NodePtr;
  10.  
  11. NodePtr sort(NodePtr list){
  12.    
  13.     NodePtr bfrBig=NULL, Big=NULL, prev = NULL, temp = list;
  14.    
  15.     int save=0;
  16.    
  17.     //Jika hanya 1 data
  18.     if(list->next==NULL) {
  19.     return list;
  20. }
  21.    
  22.         //printf("1");
  23.     //Cari nilai terbesar
  24.     while(temp != NULL){
  25.         if (temp->num > save){
  26.             save = temp->num;
  27.             Big= temp;
  28.            
  29.             if(prev != NULL)
  30.                 bfrBig=prev;
  31.            
  32.         }
  33.         prev =temp;
  34.         temp=temp->next;
  35.     }
  36.    
  37.     //Pemindahan nilai terbesar ke depan
  38.     if(bfrBig!=NULL)
  39.         bfrBig->next= Big->next;
  40.     if(Big!=list)
  41.         Big->next=list;
  42.     list=Big;
  43.     list->next= sort(list->next);
  44.    
  45.     return list;
  46. }
  47.  
  48. void printlist(NodePtr list)
  49. {
  50.     NodePtr temp = list;
  51.     do{
  52.         printf("%d ", temp->num);
  53.         temp=temp->next;
  54.     }while(temp!=NULL);
  55.     printf("\n");
  56. }
  57.  
  58. NodePtr newNode(int n)
  59. {
  60.     NodePtr np = (NodePtr) malloc(sizeof (NodePtr));
  61.     np -> num = n;
  62.     np -> next = NULL;
  63.     return np;
  64. }
  65.  
  66.  
  67. int main(){
  68.     NodePtr np, tail;
  69.     NodePtr head =NULL;
  70.     int n;
  71.     //Masukkan nilai,  masukkan 0 untuk berhenti
  72.     if (scanf("%d", &n) != 1) n = 0;
  73.     while(n!=0){
  74.         np = newNode(n);
  75.         if(head== NULL) head = np;
  76.         else tail->next = np;
  77.         tail = np;
  78.        
  79.         if (scanf("%d", &n) != 1) n = 0;
  80.     }
  81.    
  82.     printlist(head);
  83.     printlist(sort(head));
  84. }
Advertisement
Add Comment
Please, Sign In to add comment