[Leedcode 61] Rotate List

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 .

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Rotateright (ListNode head,intk) {//The subject is very easy to make mistakes!! //there is an implied condition, when the K value is greater than the length of the list, you need to take the mold, and according to the results of the flip, so must first find out the length of the linked list//two methods of solving the subject://Solution One: To find the length of the chain table, Update K, and then use the double pointer, a fast and slow, found to split the point, the list is divided into two. //Note A problem, the newly found K if equal to 0, the representative does not need to flip, directly return can//solution Two: In the chain table length, only need to traverse to the tail node, and the tail node and the head nodes are connected,//the rest of the task only needs a pointer, find the split node, the next position of the node null, return the node's original next can        /*Solution One: if (head==null| |        k==0) return head;        int len=0;        ListNode Temp=head;            while (temp!=null) {temp=temp.next;        len++;        } int Dis=k%len;        if (dis==0) return head;/////ListNode fast=head;        ListNode Slow=head;        Temp=head;            while (dis>0) {fast=fast.next;        dis--;            } while (Fast.next!=null) {fast=fast.next;        Slow=slow.next;        } Temp=slow.next;        Slow.next=null;        Fast.next=head; return temp;*/        if(head==NULL|| k==0)returnHead; intLen=1; ListNode Temp=Head;  while(temp.next!=NULL) {len++; Temp=Temp.next; } Temp.next=Head; intdis=len-k%Len;  while(dis>0) {Temp=Temp.next; Dis--; } head=Temp.next; Temp.next=NULL; returnHead; }}

[Leedcode 61] Rotate List

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.