Leetcode.61.旋转链表–每日一题
题目难度:简单
题目:原题链接
直接把草稿贴上来啦
/**
* 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) {
//当k为0或者链表为空或者链表只有一个节点时返回头节点
if (k == 0 || head == null || head.next == null) {
return head;
}
//统计链表长度
int n = 1;
ListNode p = head;
while (p.next != null) {
p = p.next;
n++;
}
int add = n - k % n;
if (add == n) {
return head;
}
//成环
p.next = head;
while (add-- > 0) {
p = p.next;
}
ListNode res = p.next;
p.next = null;
return res;
}
}