Created
October 9, 2020 00:42
-
-
Save halirutan/1509b9c45e7df460418fe255929321f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
struct ListNode | |
{ | |
int val; | |
struct ListNode *next; | |
}; | |
int getSize(struct ListNode *head) | |
{ | |
int size = 0; | |
while (head) { | |
size++; | |
head = head->next; | |
} | |
return size; | |
} | |
struct ListNode *rotateRight(struct ListNode *head, int k) | |
{ | |
int size = getSize(head); | |
if (size == 0) { | |
return head; | |
} | |
struct ListNode *current = head; | |
struct ListNode *split, *end; | |
k = k % size; | |
k = size - k; | |
if (k == 0) { | |
return head; | |
} | |
int i = 1; | |
while (current) { | |
if (i == k) { | |
split = current; | |
} | |
end = current; | |
current = current->next; | |
++i; | |
} | |
end->next = head; | |
head = split->next; | |
split->next = NULL; | |
return head; | |
} | |
int main() | |
{ | |
struct ListNode n7 = {7, NULL}; | |
struct ListNode n6 = {6, &n7}; | |
struct ListNode n5 = {5, NULL}; | |
struct ListNode n4 = {4, &n5}; | |
struct ListNode n3 = {3, &n4}; | |
struct ListNode n2 = {2, &n3}; | |
struct ListNode n1 = {1, &n2}; | |
struct ListNode *result = rotateRight(&n1, 2); | |
printf("\nSize: %d\n", getSize(result)); | |
while (result != NULL) { | |
printf("%d ", result->val); | |
result = result->next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment