leetcode61.旋转链表
整体的思路是求出实际上要旋转的大小,然后裁剪后k个元素拼接到整个链表的头
/*** 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;int n = 0;//记录整个链表长度ListNode cur = head;//求链表长度while (cur != null) {n++;cur = cur.next;}//求真实旋转长度k = k % n;if (k == 0) {//说明无需旋转return head;}//将后n-k个节点剪切到整个链表的头即旋转成功cur=head;for(int i=1;i<n-k;i++)cur=cur.next;ListNode newHead = cur.next;cur.next = null;cur = newHead;while (cur.next != null) {cur = cur.next;}cur.next = head;head = newHead;return head;}
}