[leetcode 61] Rotate List
2014-12-28 10:26
387 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
/** * 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 || !head->next || k == 0) { return head; } ListNode dummy(-1); auto p = head; int len = 1; while (p->next) { p = p->next; len++; } p->next = head; k = len - k%len; for (int i = 0; i < k; i++) { p = p->next; } dummy.next = p->next; p->next = NULL; return dummy.next; } };
相关文章推荐
- Leetcode:61. Rotate List
- [leetcode] 【链表】 61. Rotate List
- LeetCode *** 61. Rotate List
- leetcode-Rotate List-61
- LeetCode 61. Rotate List
- 【LEETCODE】61- Rotate List [Python]
- [leetcode-61]Rotate List(c)
- <LeetCode OJ> 61. Rotate List
- [LeetCode]problem 61. Rotate List
- LeetCode题解-61-Rotate List
- [Leetcode]61. Rotate List
- leetcode 61. Rotate List 向右旋转k个元素 + 链表环遍历
- LeetCode 61 — Rotate List(C++ Java Python)
- 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(Python详解及实现)