题解 | #旋转链表#
旋转链表
https://www.nowcoder.com/practice/1ad00d19a5fa4b8dae65610af8bdb0ed
using System; using System.Collections.Generic; /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode rotateLinkedList (ListNode head, int k) { // write code here // write code here if (head == null) return null; List<int> lsN = new List<int>(); ListNode lnR = head; while (head != null) { lsN.Add(head.val); head = head.next; } int nLen = lsN.Count; k = k % nLen; if (k == 0) return lnR; List<int> lsNT = lsN.GetRange(lsN.Count - k, k); //lsNT.Reverse();//反序 lsN.InsertRange(0, lsNT); head = lnR; for (int i = 0; i < nLen; i++) { head.val = lsN[i]; head = head.next; } return lnR; } }