k
places, where k is non-negative.Wrong solution 1:
public ListNode rotateRight(ListNode head, int k) {
// write your code here
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head;
for (int i = 0; i < k; i++) {
fast = fast.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
fast.next = head;
head = slow.next;
slow.next = null;
return head;
}
WA
if k is greater than the length of the linked list, it needs to mod the length of the linked list
Solution 2:
public ListNode rotateRight(ListNode head, int k) {
// write your code here
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;//new ListNode(0);
//slow.next = head;
ListNode fast = head;
int length = getLength(head);
for (int i = 0; i < (k % length); i++) {
fast = fast.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
fast.next = head;
head = slow.next;
slow.next = null;
return head;
}
private int getLength(ListNode head) {
int length = 0;
ListNode dummy = head;
while(dummy != null) {
length++;
dummy = dummy.next;
}
return length;
}
No comments:
Post a Comment