3o_3v

Untitled

Apr 5th, 2022
59
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 list{
  5.     int value;
  6.     struct list* next;
  7. } node;
  8.  
  9. node* reformat(node* first, int number, node* thisnode){
  10.     while(number && thisnode->next){
  11.         thisnode = thisnode->next;
  12.         number--;
  13.     }
  14.     if(first != thisnode){
  15.         node* last = thisnode;
  16.         while(last->next){
  17.             last = last->next;
  18.         }
  19.         node* prev = first;
  20.         node* prev_of_prev = NULL;
  21.         while(prev->next != thisnode){
  22.             prev_of_prev = prev;
  23.             prev = prev->next;
  24.         }
  25.         if(prev_of_prev){
  26.             prev_of_prev->next = thisnode;
  27.         }else{
  28.             first = thisnode;
  29.         }
  30.         prev->next = NULL;
  31.         last->next = prev;
  32.         return reformat(first, number, thisnode);
  33.     }else{
  34.         return first;
  35.     }
  36. }
  37.  
  38. node* add_node(node* list, int value){
  39.     node* prev = NULL;
  40.     node* thisnode = list;
  41.     while(thisnode){
  42.         prev = thisnode;
  43.         thisnode = thisnode->next;
  44.     }
  45.     node* new = malloc(sizeof(node));
  46.     new->next = NULL;
  47.     new->value = value;
  48.     if(prev == NULL) return new;
  49.     prev->next = new;
  50.     return list;
  51. }
  52.  
  53. void printlist(node* list){
  54.     while(list){
  55.         printf("%d ", list->value);
  56.         list = list->next;
  57.     }
  58.     printf("\n");
  59. }
  60.  
  61. int main(void) {
  62.     node* list = NULL;
  63.     for(int i = 0; i < 10; i++){
  64.         list = add_node(list, i);
  65.     }
  66.     printlist(list);
  67.     list = reformat(list, 5, list);
  68.     printlist(list);
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment