Rotate List -- leetcode
2015-04-02 10:12
232 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
在leetcode上实际执行时间为16ms。
基本思路:
1. 统计链表长度 count
2.首尾相接,做成循环链表。
3.从头再移动到第 count - k 结点,在此断开。
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
在leetcode上实际执行时间为16ms。
基本思路:
1. 统计链表长度 count
2.首尾相接,做成循环链表。
3.从头再移动到第 count - 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 (!head || !head->next || !k) return head; int count = 1; ListNode *p = head; while (p->next) { ++count; p = p->next; } p->next = head; k = k % count; k = count - k; while (k--) p = p->next; head = p->next; p->next = 0; return head; } };
相关文章推荐
- [leetcode] 61. Rotate List
- [Leetcode] 61. Rotate List
- 【LeetCode题解】61_旋转链表(Rotate-List)
- Rotate List -- LeetCode
- LeetCode: Rotate List [060]
- LeetCode 061 Rotate List
- [LeetCode]Rotate List
- LeetCode2.2.6(Rotate List)
- 【LeetCode-61】Rotate List
- leetcode - Rotate List
- Leetcode 61. Rotate List
- Rotate List - Leetcode
- [LeetCode]Rotate List
- LeetCode-Rotate List
- LeetCode(60)RotateList
- [Leetcode]61. Rotate List @python
- leetcode:单链表之Rotate List
- leetcode61 Rotate List
- 【Leetcode】【python】Rotate List
- [leetcode] Rotate List