Daily algorithm forty-three: Rotate list (the list rotates k elements)

Source: Internet
Author: User

Given a list, rotate the list to the right by K places, where k is non-negative.

For example:
Given1->2->3->4->5->NULLAnd k =2,
Return4->5->1->2->3->NULL.

K here may be a number larger than the length of the linked list, so the actual rotation position is K % Len (list ). If the calculation result is equal to zero or Len (list), the list does not need to be rotated.

Next, if the case shows a normal situation, you can complete the rotation in three steps.

(1) The first secondary pointer shifts K positions from the beginning to the back.

(2) The Second secondary Pointer Points to the header pointer, and then the two pointers move backward at the same time, knowing that the first secondary Pointer Points to the end node.

(3) declare that the third secondary Pointer Points to the successor node of the Second secondary pointer as the new header pointer to be returned. Set the successor of the second pointer to a null pointer, and point the successor of the first pointer to the original pointer. The pointer rotation can be completed here.

Note: The other method provided at the end is more concise and efficient. We recommend that you take a look at it first.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *rotateRight(ListNode *head, int k){if(head == NULL || k <= 0)return head;ListNode *temp = head;int node_count = 0;while(temp != NULL){    node_count++;    temp = temp->next;}if(k > node_count)   k = k%node_count;if(k == node_count || k == 0)   return head;ListNode *first = head;while(/*first != NULL && first->next != NULL &&*/ k > 0){first = first->next;k--;}//if(k > 0)//return head;ListNode *second = head;while(first->next != NULL){first = first->next;second = second->next;}ListNode *newhead = second->next;first->next = head;second->next = NULL;return newhead;}};

Note that at the first completion, there is no remainder part in the code, because the number of digits in the cyclic shift is longer than the length of the linked list, after the remainder part is added, the original code (that is, the part commented out now) is no longer needed. At this time, K must be smaller than the length of the linked list. Therefore, these judgments are not necessary.

Below are some online answers for your reference.

 ListNode *rotateRight(ListNode *head, int k) {          // Start typing your C/C++ solution below          // DO NOT write int main() function          if (head == NULL || head->next == NULL || k == 0) {              return head;          }                    int length = 0;          ListNode *ptr = head, *tail = head;          while (ptr != NULL) {              length++;              tail = ptr;              ptr = ptr->next;           }          k %= length;                    ptr = head;          for (int i = 0; i < length - k - 1; i++) {              ptr = ptr-> next;          }                    tail->next = head;          head = ptr->next;          ptr->next = NULL;                    return head;      }  
Another more concise method.

ListNode *rotateRight(ListNode *head, int k)    {        if(head==NULL)return NULL;        ListNode *p=head;        int n=0;        while(p->next)        {            p=p->next;            n++;        }        n++;        k=k%n;        p->next=head;        ListNode *q=head;        for(int i=0;i<n-k-1;i++)        q=q->next;        head=q->next;        q->next=NULL;            return head;    }



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.