[Leetcode] 61. Rotate List Java

Source: Internet
Author: User

Topic:

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

Example:

k = 2,return 4->5->1->2->3->null.

test instructions and analysis: flips a linked list from right to left Nth point. The main point is to find the flip point and the flip point in front of a dot, and then set the last point of next to head, the flip point of the previous point of the next set to NULL, return to the flip point.

Code:

/** * Definition for singly-linked list. * public class ListNode {*     int val; *     ListNode Next; *     listnode (int x) {val = x;}}} */public class Soluti On {public    ListNode rotateright (listnode head, int n) {        if (head = = NULL | | n==0) return head;        int length = 1;     How long does the record chain list have        listnode p = head;        while (p.next! = null) {            p = p.next;            length++;        }        At this point P points to the last point of the list        n=n%length;        if (n==0) return head;        ListNode rotednode = null;        ListNode prerotate = head;        int k=0;        while (k<length-n-1) {            prerotate = Prerotate.next;            k++;        }        Rotednode = Prerotate.next;        Prerotate.next = null;        P.next = head;        return rotednode;}    }

[Leetcode] 61. 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.