Java rotate list solution


  • 0
    V

    /**

    • Definition for singly-linked list.
    • public class ListNode {
    • int val;
      
    • ListNode next;
      
    • ListNode(int x) {
      
    •     val = x;
      
    •     next = null;
      
    • }
      
    • }
      */

    public class Solution {

    public ListNode rotateRight(ListNode head, int k) {
        
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
        
        ListNode dummy1 = head;
        int length = 0;
        
        while(dummy1 != null){
            length++;
            dummy1 = dummy1.next;
        }
        
        k = k % length;
        
        if(k == 0){
            return head;
        }
        
        ListNode point1 = head;
        ListNode point2 = head;
        ListNode dummyHead = head;
        
        for(int i = 0; i < k; i++){
            point2 = point2.next;
        }
        
        while(point2.next != null){
            point1 = point1.next;
            point2 = point2.next;
        }
        
        point2.next = dummyHead;
        ListNode newHead = point1.next;
        point1.next = null;
        
        
        return newHead;
        
    }
    

    }


Log in to reply
 

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