【LeetCode】Rotate List 解题报告
2014-12-17 17:41
375 查看
【题目】
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
【解析】
题意:把链表循环右移k个结点。
不是很难,主要是几个易错点:1)k 可能大于等于链表长度!!!2)链表为空或长度为1。
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->NULLand k =
2,
return
4->5->1->2->3->NULL.
【解析】
题意:把链表循环右移k个结点。
不是很难,主要是几个易错点:1)k 可能大于等于链表长度!!!2)链表为空或长度为1。
/** * 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) { if (head == null || n < 1) return head; //遍历链表求其长度,并找到尾部 ListNode node = head; ListNode tail = null; ListNode newhead = null; int len = 0; while (node != null) { len++; tail = node; node = node.next; } //只有一个结点时,返回原链表即可 if (len == 1 || n % len == 0) return head; //把链表首位拼接 tail.next = head; //找到右移后的链表尾部 node = head; int i = 1; while (i != len - n % len) { i++; node = node.next; } newhead = node.next; node.next = null; return newhead; } }
相关文章推荐
- LeetCode解题报告—— Rotate List & Set Matrix Zeroes & Sort Colors
- LeetCode61 Rotate List 解题报告
- LeetCode: Rotate List 解题报告
- [leetcode]61. Rotate List@Java解题报告
- [leetcode] 61. Rotate List 解题报告
- [LeetCode] Rotate List 解题报告
- [LeetCode] Rotate List 解题报告
- Leetcode Insertion Sort List 解题报告
- LeetCode — Linked List Cycle II 解题报告
- LeetCode Sort List 解题报告
- LeetCode: Rotate Image 解题报告
- leetCode解题报告之Sort List
- Leetcode Sort List 解题报告
- [LeetCode] Rotate Image 解题报告
- 【LeetCode】Reorder List 解题报告
- LeetCode 解题报告 Sort List
- LeetCode解题报告:Reorder List
- LeetCode—Reorder List 解题报告
- Leetcode Insertion Sort List 解题报告
- LeetCode—Insertion Sort List 解题报告