Created
October 11, 2017 17:05
-
-
Save shailrshah/b0f4d2faa489fd35abbd527440615a75 to your computer and use it in GitHub Desktop.
Rotate List: Given a list, rotate the list to the right by k places, where k is non-negative. (https://leetcode.com/problems/rotate-list/description/)
This file contains hidden or 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
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { val = x; } | |
* } | |
*/ | |
class RotateListRight { | |
static int getLength(ListNode head) { | |
int n = 0; | |
for(ListNode help = head; help!=null; help = help.next, n++); | |
return n; | |
} | |
static ListNode getLastNode(ListNode head){ | |
ListNode help; | |
for(help = head; help.next != null; help = help.next); | |
return help; | |
} | |
public ListNode rotateRight(ListNode head, int k) { | |
int length = getLength(head); | |
if(length == 0 || k%length == 0) | |
return head; | |
// 1. Point current last node to head node | |
// 2. Find new last node | |
// 3. Find new head node | |
// 4. Make the new last node as the last node | |
// 5. Make the new head node as the head node | |
ListNode lastNode = getLastNode(head); | |
lastNode.next = head; | |
int cutPoint = length - (k % length) - 1; | |
ListNode help = head; | |
for(int i = 0; i != cutPoint; i++){ | |
help = help.next; | |
} | |
ListNode newLastNode = help; | |
ListNode newHead = help.next; | |
newLastNode.next = null; | |
head = newHead; | |
return head; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment