[LeetCode]Rotate List

题目描述:(链接)

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.

解题思路:

注意k会大于链表长度: k % length.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* rotateRight(ListNode* head, int k) {
12         if (!head || k == 0) return head;
13         
14         int length = 1;
15         ListNode *cur = head;
16         for (; cur->next != nullptr ; cur = cur->next) {
17             ++length;
18         }
19         k = length - k % length;
20         
21         cur->next = head;
22         for (int i =0; i < k; i++) {
23             cur = cur->next;
24         }
25         
26         head = cur->next;
27         cur->next = nullptr;
28         
29         return head;
30     }
31 };

 

posted @ 2015-10-27 23:33  skycore  阅读(145)  评论(0编辑  收藏  举报