leetcode -- Rotate List
2013-08-12 23:38
176 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
[解题思路]
初始的想法是类似于求倒数第k个数,结果发现k可能会比len大,到网上搜索了下:
从head节点开始跑,一直跑到尾节点,得到len,将尾节点的next指针指向head,接着跑(len -n) % len步,断开
这里需注意(len -n) % len可能为负数,需+len
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
[解题思路]
初始的想法是类似于求倒数第k个数,结果发现k可能会比len大,到网上搜索了下:
从head节点开始跑,一直跑到尾节点,得到len,将尾节点的next指针指向head,接着跑(len -n) % len步,断开
这里需注意(len -n) % len可能为负数,需+len
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode rotateRight(ListNode head, int n) { // Start typing your Java solution below // DO NOT write main() function if(head == null || n == 0){ return head; } int len = 1; ListNode p = head; while(p.next != null){ len ++; p = p.next; } p.next = head; /* int count = (len - n - 1) % len; while(count < 0){ count += len; count %= len; } p = head; */ int count = (len - n) % len; while(count < 0){ count += len; count %= len; } int step = 0; while(step < count){ p = p.next; step ++; } head = p.next; p.next = null; return head; } }
相关文章推荐
- [LeetCode]Rotate List
- leetcode第一刷_Rotate List
- LeetCode-Rotate List
- [Leetcode]Rotate List
- LeetCode: Rotate List
- LeetCode 61. Rotate List
- LeetCode 61. Rotate List
- LeetCode----- 61. Rotate List
- [LeetCode61]Rotate List
- Leetcode 061 Rotate List
- LeetCode | Rotate List
- Leetcode 61. Rotate List
- [LeetCode]Rotate List
- [Leetcode] Rotate List
- LeetCode-Rotate List
- [leetcode][list] Rotate List
- Rotate List--LeetCode
- [LeetCode] Rotate List
- Rotate List || LeetCode
- 【leetcode】Rotate List