/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode RotateRight(ListNode head, int k) { if(head == null){ return null; } var len = LenOf(head); if(len < 2 || k == len || k < 1){ return head; } if(k > len){ k = k % len; } var stack = new Stack(); var p = head; for(var i = 0;i < len - k - 1;i ++){ p = p.next; } var q = p; p = p.next; while(p != null){ stack.Push(p.val); p = p.next; } q.next = null; while(stack.Count > 0) { var n = new ListNode(stack.Pop()); n.next = head; head = n; } return head; } private int LenOf(ListNode head) { var p = head; var len = 0; while(p != null){ len ++; p = p.next; } return len; } }