C# Solution


  • 0
        public ListNode RotateRight(ListNode head, int k) {
                ListNode newHead = null,
                        fastNode = head,
                        slowNode = head,
                        lastNode = head;
                int counter = 1,
                    index = k,
                    length = 1;
    
                while (lastNode != null && lastNode.next != null)
                {
                    length++;
                    lastNode = lastNode.next;
                }
                index = k % length;
    
                if (index == 0 || head == null || head.next == null)
                    return head;
    
                index++;
    
                while (counter <= index)
                {
                    fastNode = fastNode.next;
                    counter++;
                }
    
                while (fastNode != null)
                {
                    slowNode = slowNode.next;
                    fastNode = fastNode.next;
                }
    
                newHead = slowNode.next;
                slowNode.next = null;
                lastNode.next = head;
    
                return newHead;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.