Practice #3
Lesson 12 of 14 in Coddy's Doubly Linked List - Data Structures Series #6 course.
Challenge
EasyWrite a function rotateRight that gets an integer array arr (the values of a doubly linked list) and an integer k, and returns the array rotated right by k positions.
If k is larger than the length, only the remainder matters (rotating by n brings you back to where you started). If the list is empty, return an empty array.
Use a doubly linked list to solve this problem!
You must use the DoublyLinkedList class (provided in doublylinkedlist.<ext> along with node.<ext>) — do not use language built-ins like arrays' reverse, slicing, sort, or stdlib list operations to compute the result.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "solution.h"
int main() {
char line1[8192];
char line2[64];
if (!fgets(line1, sizeof(line1), stdin)) line1[0] = '\0';
if (!fgets(line2, sizeof(line2), stdin)) line2[0] = '\0';
int arr[4096];
int len = 0;
char* tok = strtok(line1, " \t\r\n");
while (tok) { arr[len++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
int n = atoi(line2);
int rs = 0;
int* r = rotateRight(arr, len, n, &rs);
for (int idx = 0; idx < rs; idx++) {
if (idx > 0) printf(" ");
printf("%d", r[idx]);
}
printf("\n");
return 0;
}