Advertisement
Guest User

move_to_front

a guest
Apr 29th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.53 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct _Node{
  5.     int value;
  6.     struct _Node *next;
  7. } Node;
  8.  
  9. void printList(Node *head){
  10.     if(head==NULL) return;
  11.     printf("%d\n", head->value);
  12.     printList(head->next);
  13. }
  14.  
  15. int search(Node *head, int query){
  16.     int res = 0;
  17.  
  18.     while(head!=NULL){
  19.         if(head->value == query) return res;
  20.         head = head->next;
  21.         res++;
  22.     }
  23.  
  24.     return (-1);
  25. }
  26.  
  27. void moveFront(Node *head, int query){
  28.     Node *curr = head;
  29.     Node *prev = NULL;
  30.  
  31.     int found=0;
  32.     while(!found){
  33.        
  34.         if(curr->value == query){
  35.             found=1;
  36.         }
  37.        
  38.         else{
  39.             prev = curr;
  40.             curr = curr->next;
  41.         }
  42.     }  
  43.  
  44.     if(prev!=NULL){
  45.         printf("***Not first element***\n");
  46.         prev->next = curr->next;
  47.         curr->next = head->next;
  48.         head = curr;
  49.     }
  50. }
  51.  
  52. int main(){
  53.     Node *head = malloc(sizeof(Node));
  54.     Node *last = head;
  55.  
  56.     int n;
  57.     scanf("%d", &n);
  58.  
  59.     int i, input;
  60.     for(i=0; i<n; i++){
  61.         scanf("%d", &input);
  62.  
  63.         Node *new = malloc(sizeof(Node));
  64.         new->value = input;
  65.         new->next = NULL;
  66.  
  67.         if(i==0){
  68.             head = new;
  69.             last = new;
  70.         }
  71.  
  72.         else{
  73.             last->next = new;
  74.             last = new;
  75.         }
  76.     }
  77.  
  78.     printf("***Print List***\n");
  79.     printList(head);
  80.  
  81.     printf("***Query Section***\n");
  82.  
  83.     int flag=1, query, position;
  84.     while(flag){
  85.         scanf("%d", &query);
  86.  
  87.         position = search(head, query);
  88.  
  89.         if(position>=0){
  90.             printf("%d\n", position);
  91.             moveFront(head, query);
  92.             printf("***Print List***\n");
  93.             printList(head);
  94.         }
  95.         else{
  96.             flag = 0;
  97.             printf("-1\n");
  98.         }
  99.     }
  100.  
  101.     printf("***Program Ended***\n");
  102.  
  103.     return 0;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement