Leetcode Rotate List-----java

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 .
The problem is not difficult, that is, to give a number k, and then from right to left number K node, and then start with this node, re-form a linked list.

It is important to note that if K is greater than the list length len, then k = K%len

The trick is that when you k<len, you can count the number of K from front to back, and then walk backwards from the current position (flag) and head to the end, which is a bit more efficient.

But the first time is not very fast, time consuming 15ms.

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Rotateright (ListNode head,intk) {if(k = = 0 | | head = =NULL){            returnHead; } ListNode Flag=Head; intLen;  for(len = 1;len < K && Flag.next! =NULL; len++) {flag=Flag.next; }        if(len = =k) {            if(Flag.next = =NULL)                returnHead; ListNode result=Head; Flag=Flag.next;  while(Flag.next! =NULL) {result=Result.next; Flag=Flag.next; } Flag.next=Head; Flag=Result.next; Result.next=NULL; returnFlag; } ListNode Last=Flag; if(k >Len) k= len-k%Len; Elsek= len-K; if(k = = 0 | | k = =len)returnHead; Flag=Head;  for(inti = 1;i<k; i++) {flag=Flag.next; } Last.next=Head; Head=Flag.next; Flag.next=NULL; returnHead; }}

Then looked at the online 1ms answer, in fact, there is no difference, and then take their run, the results of 15, 16ms, so the Leetcode site itself (perhaps a Java Virtual machine) problem.

Leetcode Rotate List-----java

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.