61. Rotate List, 61 rotatelist

Source: Internet
Author: User

61. Rotate List, 61 rotatelist

Given a list, rotate the list to the rightKPlaces, whereKIs non-negative.

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

K = 2 is to move to the right twice

1/** 2 * Definition for singly-linked list. 3 * struct ListNode {4 * int val; 5 * struct ListNode * next; 6 *}; 7 */8 struct ListNode * rotateRight (struct ListNode * head, int k) {9 struct ListNode * cur; 10 cur = head; 11 int n = 1; 12 if (head = NULL) 13 return NULL; 14 while (cur-> next! = NULL) // calculate the length of the linked list and locate cur to the End Node 15 {16 cur = cur-> next; 17 n ++; 18} 19 k = n-k % n; // note that K may be greater than the length of the linked list. The remainder is 20 cur-> next = head; 21 cur = head; 22 k --; 23 while (k) // move the cur to the location 24 {25 cur = cur-> next; 26 k --; 27} 28 head = cur-> next; 29 cur-> next = NULL; 30 return head; 31}

 

Related Article

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.