LeetCode 92 Rotate List
2014-10-27 13:45
477 查看
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.
分析:
将链表后面一部分移动到前面,思路是先连成环,再在合适的地方断开。
这里k有可能超过链表长度,因此要有个取余操作。
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
分析:
将链表后面一部分移动到前面,思路是先连成环,再在合适的地方断开。
这里k有可能超过链表长度,因此要有个取余操作。
/** * 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) { //这里有个问题,就是k有可能大于链表长度 if(head == null || head.next == null) return head; ListNode point = head; int len = 1; while(point.next != null){ point = point.next; len++; } point.next = head;//连成环 int count = len - n%len; while(count > 0){ point = point.next; count--; } head = point.next;//断开环 point.next = null; return head; } }
相关文章推荐
- 【LeetCode】Rotate List
- leetcode -- Rotate List -- 重点
- leetcode 61. Rotate List
- LeetCode92 Reverse Linked List II
- [Leetcode] Rotate List
- LeetCode-Rotate List-旋转链表-旋转操作和链表
- LeetCode92 Reverse Linked List II
- leetcode — rotate-list
- (LeetCode 92)Reverse Linked List II
- leetcode解题方案--061--RotateList
- [Leetcode] 61. Rotate List
- Leetcode: Rotate List
- [LeetCode] Rotate List
- LeetCode之Rotate List
- leetcode-Rotate List-61
- LeetCode - Rotate List
- LeetCode Rotate List 分析解答
- [LeetCode]Rotate List
- [leetcode 92] Reverse Linked List II
- leetcode 61 --Rotate List 链表 循环/断开 翻转