Advertisement
informaticage

Recurion list reverse with cheat

Jan 27th, 2024
1,024
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. struct Node {
  4.   int value;
  5.   int next;
  6. };
  7.  
  8. void print_list(Node list[], int index = 0) {
  9.   if(index == -1) return;
  10.   std::cout << list[index].value << " ";
  11.   print_list(list, list[index].next);
  12. }
  13.  
  14. int store_list(Node list[], int copy[], int index = 0, int iteration = 0) {
  15.   if(index == -1) return iteration;
  16.   copy[iteration] = list[index].value;
  17.   return store_list(list, copy, list[index].next, iteration + 1);
  18. }
  19.  
  20. void write_on_list(Node list[], int copy[], int index, int iteration) {
  21.   if(index == -1 || iteration == -1) return;
  22.   list[index].value = copy[iteration - 1];
  23.   write_on_list(list, copy, list[index].next, iteration - 1);
  24. }
  25.  
  26. void reverse_list(Node list[], int length) {
  27.   int* copy = new int[length];
  28.   int real_len = store_list(list, copy);
  29.   write_on_list(list, copy, 0, real_len);
  30. }
  31.  
  32. int main(void) {
  33.   Node list[5] = {
  34.       {1, 4}, { 9, -1 }, {3, 1}, {}, {5, 2},
  35.   };
  36.  
  37.   print_list(list);
  38.   reverse_list(list, 5);
  39.   print_list(list);
  40.   return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement