Leetcode double pointer rotating linked list java

Title description
Given a linked list, rotate the linked list and move each node of the linked list k positions to the right, where k is a non-negative number.

Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
Rotate 1 step to the right : 5->1->2->3->4->NULL
Rotate right 2 steps: 4->5->1->2->3->NULL

Ideas:

  1. If the linked list is empty, return null
  2. If the linked list has only one head node, no matter how it is rotated, it is the linked list itself, return head
  3. Because moving the len multiple of k to the right has the same effect as moving k (len is the length of the linked list), first find the length of the linked list
 ListNode tail = head;
        int len ;
        for(len = 1;tail.next != null;len++){
    
    
            tail = tail.next;
        }
  k = k%len;
  1. Define two pointers, fast fast pointer and slow slow pointer, fast moves k steps first, if fast and slow point to the same, head is returned, otherwise fast and slow move together until fast.next is empty
  2. Point the next of fast to the head node, and change the head node to the next node of slow, and the next node of slow is empty

Code:

/**
 * 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;
        }
        if(head.next == null){
    
    
            return head;
        }
        ListNode tail = head;
        int len ;
        for(len = 1;tail.next != null;len++){
    
    
            tail = tail.next;
        }
        k = k%len;
        ListNode fast = head;
        ListNode slow = head;
        for(int i = 0;i<k;i++){
    
    
            fast = fast.next;
        }
        if(fast == slow){
    
    
            return head;
        }
        while(fast.next != null){
    
    
            fast = fast.next;
            slow = slow.next;
        }
        fast.next = head;
        head = slow.next;
        slow.next = null;
        return head;
    }
}

Guess you like

Origin blog.csdn.net/stonney/article/details/112135978