Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@halirutan
Created October 9, 2020 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halirutan/1509b9c45e7df460418fe255929321f5 to your computer and use it in GitHub Desktop.
Save halirutan/1509b9c45e7df460418fe255929321f5 to your computer and use it in GitHub Desktop.
#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