Last active
March 23, 2019 05:51
-
-
Save unnisworld/e9888731037c60b87bfe30de0e435c51 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
package dsa; | |
public class LinkedListRotate { | |
public static void main(String[] args) | |
{ | |
ListNode n1 = new ListNode(1); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(3); ListNode n4 = new ListNode(4); ListNode n5 = new ListNode(5); | |
n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; | |
System.out.println(getLength(n1)); | |
print(n1); | |
ListNode head = rotateRight(n1, 1); | |
print(head); | |
} | |
public static ListNode rotateRight(ListNode head, int k) { | |
int len = getLength(head); | |
if (len <= 1 || k == 0 || len == k) { | |
return head; | |
} | |
int r = k % len; | |
if( r == 0) { | |
return head; | |
} | |
// New head's location is (len - r). | |
// Get the location of newHead and it's predecessor. | |
ListNode newHeadsPredecessor = head; | |
for(int i=1;i< len-r;i++) { | |
newHeadsPredecessor = newHeadsPredecessor.next; | |
} | |
ListNode newHead = newHeadsPredecessor.next; | |
// Set newHead's predecessor as the new endnode. | |
newHeadsPredecessor.next = null; | |
// Go to the current endNode. | |
ListNode endNode = newHead; | |
while(endNode.next != null) { | |
endNode = endNode.next; | |
} | |
// connect it to current head node | |
endNode.next = head; | |
// elevate the new-head as head node. | |
return newHead; | |
} | |
private static void print(ListNode head) { | |
while(head != null) { | |
System.out.print(head.val + "->"); | |
head = head.next; | |
} | |
System.out.println(); | |
} | |
private static int getLength(ListNode head) { | |
int len = 0; | |
while(head != null) { | |
head = head.next; | |
len++; | |
} | |
return len; | |
} | |
} | |
class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { val = x; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment