[LeetCode OJ 061] Rotate List

Source: Internet
Author: User

[LeetCode OJ 061] Rotate List

Question: Given a list, rotate the list to the right bykplaces, wherekis non-negative.

For example:
Given1-> 2-> 3-> 4-> 5-> NULLAndk =2,
Return4-> 5-> 1-> 2-> 3-> NULL.

Solution: A linked list must be reversed Based on the given position. The sample code is as follows:

Public class Solution {public ListNode rotateRight (ListNode head, int k) {if (head = null) return null; ListNode p = head; ListNode q = head; int num = 1; // count the number of elements in the linked list while (p. next! = Null) {num ++; p = p. next; // p points to the End Node} int n = 1; if (k> = num) k = k % num; // process the loop reversal condition while (n <num-k) {n ++; q = q. next;} ListNode h = null; if (q. next! = Null) {// use the node after q as the new header node h = q. next; q. next = null; p. next = head;} else {h = head;} return h ;}}

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.