I am trying to solve the question at
:https://leetcode.com/problems/rotate-list/
Question:
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
- Input:
1->2->3->4->5->NULL
,k = 2
- Output:
4->5->1->2->3->NULL
Explanation:
- rotate 1 steps to the right:
5->1->2->3->4->NULL
- rotate 2 steps to the right:
4->5->1->2->3->NULL
//public class ListNode
//{
// public int val;
// public ListNode next;
// public ListNode(int x) { val = x; }
//}
//k = number of places
//head =Given Linked List
public ListNode RotateRight(ListNode head, int k) {
if (k > 0 && head != null) {
ListNode tail = head,
RotatedList = null,
kthnode = head,
kthPrevNode = head;
int listLength = 0;
while (tail != null) {
listLength += 1;
tail = tail.next;
}
k = k % listLength;
if (k == 0 || listLength == 0) {
return head;
}
for (int i = 0; i < listLength - k; i++) {
kthPrevNode = kthnode;
kthnode = kthnode.next;
}
RotatedList = kthnode;
kthPrevNode.next = null;
while (kthnode.next != null) {
kthnode = kthnode.next;
}
kthnode.next = head;
return RotatedList;
}
return head;
}
}
}
I have passed all test cases but I am looking to improve code efficiency and time complexity,Kindly let me know if there are any bad practices as well