Leetcode 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 .

Analysis:

1. Compute the length of list m
2. partition list into the small list, notice that it moves exactly to the end of the list, and the next is null!!
Before list is List1, after list was list2, set last node in list1 List1.next = null
3. Concatenate the tail of the list to the head of one list

Java Code

20160601

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Rotateright (ListNode head,intk) {//1. Compute the length of list m//2. Partition list into the small list,//before list is List1, after list was list2, set last node in list1 list1.next = null//3. Concatenate the tail of the list to the head of one list//Base Case        if(Head = =NULL|| Head.next = =NULL|| K = = 0) {            returnHead; }        intm =GetLength (head); intMovestep = m-k% m-1; ListNode cur=Head; ListNode One=Head; ListNode=NULL;  while(Movestep > 0) {cur=Cur.next; Movestep--; }        if(Cur.next = =NULL) {//move to the end of the linked list, no rotate            returnHead; }=Cur.next; Cur.next=NULL; ListNode Twohead=both ;  while(Two.next! =NULL) {=Two.next; } Two.next=One ; returnTwohead; }        Private intGetLength (ListNode head) {intLen = 0;  while(Head! =NULL) {Head=Head.next; Len++; }        returnLen; }}

Leetcode 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.