[LeetCode]61. Rotate List
2017-08-13 16:44
288 查看
61. 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.
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.
// 1.注意k取值可能超过链表长度,需要取模 // 2.找到左半部分和右半部分的首尾,连接好即可 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (head == NULL) return NULL; // k 的大小可能大于链表的长度: 先计算链表长度,k = k % length ListNode* pCur = head; int length = 0; while (pCur){ ++length; pCur = pCur->next; } k = k % length; // k如果等于0,不需要旋转 if (k == 0) return head; // 原始链表:left_start ,..., left_end, right_start, ..., right_end // 旋转结果:right_start, ..., right_end, left_start, ..., left_end // 找到右半部分的前驱,也就是左半部分的最后一个结点left_end // left_start就是head,不需要寻找了 ListNode* left_end = head; for (int i = 1; i < length - k; ++i){ left_end = left_end->next; } // right_start是left_end的下一个结点 ListNode* right_start = left_end->next; ListNode* right_end = right_start; // right_end是尾结点 while (right_end->next != NULL) right_end = right_end->next; right_end->next = head; left_end->next = NULL; return right_start; } };
相关文章推荐
- [LeetCode]61. Rotate List
- LeetCode 61. Rotate List(旋转链表)
- 【LeetCode】61. Rotate List
- [leetcode] 61. Rotate List 解题报告
- [LeetCode]61 Rotate List
- leetcode: 61. Rotate List
- Leetcode61 rotate list
- LeetCode 61. Rotate List
- LeetCode - 61. Rotate List
- [LeetCode] 61. Rotate List 旋转链表
- 个人记录-LeetCode 61. Rotate List
- LeetCode-61-Rotate List 链表水题
- LeetCode-61. Rotate List
- leetcode[61]Rotate List
- 【一天一道LeetCode】#61. Rotate List
- 【leetcode】61. Rotate List【java】
- [leetcode-61]Rotate List(c)
- LeetCode61 Rotate List 解题报告
- leetcode 61 --Rotate List 链表 循环/断开 翻转
- leetcode[61]:Rotate List