Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
题意:旋转链表,k是旋转几位。
思路:对k求余,然后创建头结点,旋转起来。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) {
return head;
}
int cnt = 1;
ListNode p2 = head;
while (p2.next != null) {
cnt++;
p2 = p2.next;
}
k = k % cnt;
ListNode pHead = head;
ListNode p1 = head;
for (int i = 0; i < cnt - k - 1; i++) {
p1 = p1.next;
}
p2.next = pHead;
pHead = p1.next;
p1.next = null;
return pHead;
}
}
网友评论