[Leetcode] Rotate list single-Necklace table rotation

Source: Internet
Author: User

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

For example:
Given 1->2->3->4->5->NULL and k = 2 ,
Return 4->5->1->2->3->NULL .

Hide TagsLinked List Pointers This problem is a bit difficult to understand, K means that the list right from the first K, K is greater than the number of chains when the loop read, so the title K =5 when the direct return. The idea is to determine where the list is broken, there is a technique is a fast pointer to go through the K-times, and then the speed of the pointer once again, if the fast pointer to the tail, the slow pointer after the fast pointer k times, just right up the K step.
1#include <iostream>2 using namespacestd;3 4 /**5 * Definition for singly-linked list.6  */7 structListNode {8     intVal;9ListNode *Next;TenListNode (intx): Val (x), Next (NULL) {} One }; A  - classSolution { -  Public: theListNode *rotateright (ListNode *head,intk) { -         if(head==null| | k==0)returnhead; -         intCNT =0; -ListNode * first=head,*slow=head; +          while(cnt<k) { -             if(first==null) First =head; +First=first->Next; Acnt++; at         } -         if(First==null)returnhead; -          while(first->next!=NULL) { -First=first->Next; -Slow=slow->Next; -         } infirst->next=head; -Head = slow->Next; toSlow->next =NULL; +         returnhead; -     } the }; *  $ intMain ()Panax Notoginseng { -  the     return 0; +}
View Code

[Leetcode] Rotate list single-Necklace table rotation

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.