Rotate List
2015-07-14 08:31
211 查看
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return null;
}
if (k < 0) {
return head;
}
int length = 0;
ListNode ptr = head;
while (ptr != null) {
ptr = ptr.next;
length++;
}
int shift = k % length;
if (shift == 0) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy;
for (int i = 0; i < shift; i++) {
fast = fast.next;
}
ListNode slow = dummy;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
fast.next = dummy.next;
dummy.next = slow.next;
slow.next = null;
return dummy.next;
}
}
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return null;
}
if (k < 0) {
return head;
}
int length = 0;
ListNode ptr = head;
while (ptr != null) {
ptr = ptr.next;
length++;
}
int shift = k % length;
if (shift == 0) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy;
for (int i = 0; i < shift; i++) {
fast = fast.next;
}
ListNode slow = dummy;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
fast.next = dummy.next;
dummy.next = slow.next;
slow.next = null;
return dummy.next;
}
}
相关文章推荐
- [LeetCode] Partition List
- [LeetCode] Next Permutation
- [LeetCode]Copy List with Random Pointer
- [LeetCode]Reverse Linked List
- [LeetCode] Remove Element
- [LeetCode] Linked List Cycle
- [LeetCode] Merge Sorted Array
- [LeetCode] Merge Two Sorted Lists
- [LeetCode] Convert Sorted List to Binary Search Tree
- [LeetCode] Swap Nodes in Pairs
- [LeetCode] 3Sum Closest
- [LeetCode] 3Sum
- [leetCode] Minimum Size Subarray Sum
- [leetCode] Merge Sorted Array
- Reverse Linked List II
- Add Two Numbers
- Partition List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List II
- Rotate List