61. 旋转链表
题目:


题解:
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
//特判
if(head == null) {
return head;
}
ListNode cur = head;
int length = 0;
while(cur != null) {
cur = cur.next;
length++;
}
//k可能大于length,所以k进行取余
k%=length;
//如果k==length的时候就是原链表,当k取余后为0的时候也是原链表
if(k == length || k == 0) {
return head;
}
cur = head;
int count = 0;
ListNode h = new ListNode();
while(cur.next != null) {
count++;
if(count==length-k) {
h = cur.next;
cur.next = null;
cur = h;
}
//防止cur.next直接为空,导致cur=cur.next,将cur置为空,再进入循环判断cur.next不为空,就会报空指针异常
if(cur.next == null) {
break;
}
cur = cur.next;
}
cur.next = head;
return h;
}
}