【Leetcode】【Medium】Rotate List
2015-05-19 03:10
162 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
解题思路:
题目看上去很简单,但是需要注意一下点:
1、任何输入都有可能,即使是无效的输入(例如链表为空,k不为0),所以程序开始时的检查在任何时候都非常重要。
2、另一个边界条件,就是是否在空指针中,使用了->next操作,很多链表错误都发生在此处。
3、K是旋转的结点数,因此K可能大于整个链表的结点数。
4、K不仅可能大于结点数,还可能非常大,因此传统的循环耗费时间太多,要对K做取余操作。
代码:
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
解题思路:
题目看上去很简单,但是需要注意一下点:
1、任何输入都有可能,即使是无效的输入(例如链表为空,k不为0),所以程序开始时的检查在任何时候都非常重要。
2、另一个边界条件,就是是否在空指针中,使用了->next操作,很多链表错误都发生在此处。
3、K是旋转的结点数,因此K可能大于整个链表的结点数。
4、K不仅可能大于结点数,还可能非常大,因此传统的循环耗费时间太多,要对K做取余操作。
代码:
/** * 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 (k == 0 || !head) return head; ListNode* pre = head; ListNode* last = head; int num = 1; while (k--) { if (last->next) { num++; last = last->next; } else { k = k % num; last = head; } } while (last->next) { pre = pre->next; last = last->next; } last->next = head; head = pre->next; pre->next = NULL; return head; } }
相关文章推荐
- [Leetcode 49, medium] Anagrams
- Leetcode 148. Sort List (Medium) (cpp)
- [leetcode 78 & 90, Medium] Subsets I and II
- LeetCode的medium题集合(C++实现)六
- Leetcode: 39. Combination Sum(Week12, Medium)
- Leetcode 93. Restore IP Addresses (Medium) (cpp)
- LeetCode:105_Construct Binary Tree from Preorder and Inorder Traversal | 根据前序和中序遍历构建二叉树 | Medium
- 【Leetcode】【Medium】Construct Binary Tree from Preorder and Inorder Traversal
- 43 leetcode - Rotate List
- LeetCode解题报告 452. Minimum Number of Arrows to Burst Balloons [medium]
- LeetCode的medium题集合(C++实现)十
- LeetCode 646. Maximum Length of Pair Chain [Medium]
- LeetCode的medium题集合(C++实现)十一
- 【Leetcode】【Medium】Search a 2D Matrix
- 蜗牛慢慢爬 LeetCode 6. ZigZag Conversion [Difficulty: Medium]
- 【LeetCode】(3)Longest Substring Without Repeating Characters(Medium)
- [置顶] [编程题] LeetCode上的backTracking类型的题目-难度Medium
- 【LeetCode】280.Wiggle Sort (Medium)(带锁题)解题报告
- 蜗牛慢慢爬 LeetCode 11. Container With Most Water [Difficulty: Medium]
- Leetcode 3. Longest Substring Without Repeating Characters (Medium) (cpp)