[LeetCode] Rotate List
2017-07-19 11:23
288 查看
题目:
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步,然后快指针和慢指针同时走,这样当快指针走到末尾时,慢指针就到链表后半部分的起始结点了。k的大小有可能大于链表长度,所以先要对k取余。可以通过遍历一遍链表来计算链表长度。
需要注意的是:k取余后为0或者原链表为空的情况下,都要直接返回原链表,不然将慢指针的下一个作为新链表头会出错。
代码:
public class RotateList {
public ListNode rotateRight(ListNode head, int k) {
ListNode fast = head;
int length = 0;
//计算链表的长度
while(fast != null) {
length++;
fast = fast.next;
}
//如果不旋转或者原链表为空,则直接返回
if(head == null || k % length == 0) {
return head;
}
//恢复快指针,重新指向头结点
fast = head;
//让快指针先走k步
for(int i = 0; i < k % length; i++) {
fast = fast.next;
}
//找到新头结点的前一个节点
ListNode slow = head;
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
}
//将后半部分放到前面来
ListNode newHead = slow.next;
slow.next = null;
fast.next = head;
return newHead;
}
}
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步,然后快指针和慢指针同时走,这样当快指针走到末尾时,慢指针就到链表后半部分的起始结点了。k的大小有可能大于链表长度,所以先要对k取余。可以通过遍历一遍链表来计算链表长度。
需要注意的是:k取余后为0或者原链表为空的情况下,都要直接返回原链表,不然将慢指针的下一个作为新链表头会出错。
代码:
public class RotateList {
public ListNode rotateRight(ListNode head, int k) {
ListNode fast = head;
int length = 0;
//计算链表的长度
while(fast != null) {
length++;
fast = fast.next;
}
//如果不旋转或者原链表为空,则直接返回
if(head == null || k % length == 0) {
return head;
}
//恢复快指针,重新指向头结点
fast = head;
//让快指针先走k步
for(int i = 0; i < k % length; i++) {
fast = fast.next;
}
//找到新头结点的前一个节点
ListNode slow = head;
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
}
//将后半部分放到前面来
ListNode newHead = slow.next;
slow.next = null;
fast.next = head;
return newHead;
}
}
相关文章推荐
- Leetcode 61. Rotate List
- 【Leetcode】【python】Rotate List
- leetcode[60] Rotate List
- LeetCode Rotate List
- Leetcode: Rotate List
- [LeetCode]Rotate List
- leetcode--Rotate List
- LeetCode之“链表”:Rotate List
- LeetCode:Rotate List
- Leetcode:61. Rotate List
- LeetCode:Rotate List
- LeetCode 61 - Rotate List
- [LeetCode]61. Rotate List
- leetcode做题总结,题目Rotate List 2012/03/27
- Leetcode: Rotate List
- LeetCode 61. Rotate List
- [leetcode] Rotate List
- LeetCode-61. Rotate List
- Leetcode题集——rotate-list
- leetcode Rotate List