LeetCode61: Rotating linked list

1. 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:

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

Example 2:

输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL

Two, problem-solving ideas

  1. First determine the length of the linked list

    int length=0;
            ListNode* p=head;
            while(p!=nullptr){
          
          
                p=p->next;
                length++;
            }       
    
  2. When the linked list is empty or the length is one or move zero step or move the integral multiple of the linked list, return to the original linked list head node pointer

     if(length==0||length==1||k==0||k%length==0)
                return head;
    
  3. After the first two steps, another k=k%length, and then move a pointer to the end of the original linked list

    	k=k%length;
        p=head;
        while(p->next!=nullptr){
          
          
        	p=p->next;
        }
    
  4. Using the double pointer method, move length-k-1 steps from the beginning to the end, then break the linked list into two and reconnect

    	ListNode* t1=head;
        ListNode* t2=head->next;
        for(int i=0;i<length-k-1;i++){
          
          
        	t1=t1->next;
            t2=t2->next;
        }
        t1->next=nullptr;
        p->next=head;
    

Three, my code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* rotateRight(ListNode* head, int k) {
    
    
        int length=0;
        ListNode* p=head;
        while(p!=nullptr){
    
    
            p=p->next;
            length++;
        }       
        if(length==0||length==1||k==0||k%length==0)
            return head;
        k=k%length;
        p=head;
        while(p->next!=nullptr){
    
    
            p=p->next;
        }
        ListNode* t1=head;
        ListNode* t2=head->next;
        for(int i=0;i<length-k-1;i++){
    
    
            t1=t1->next;
            t2=t2->next;
        }
        t1->next=nullptr;
        p->next=head;
        return t2;
    }c
};

Four, test results

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-5nlnGC14-1607787295853) (C:\Users\admin\AppData\Roaming\Typora\typora-user-images\ image-20201212230526621.png)]

Guess you like

Origin blog.csdn.net/weixin_45341339/article/details/111087038