Rotate List leetcode java
2017-08-16 21:46
423 查看
题目:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
题解:
这道题主要先理解题意,就是倒着数k个node,从那开始到结尾和之前那部分对调,那个例子就是,4->5拿前面来,1->2->3拿后面去。
几个特殊:
k是可以大于整个list的长度的,所以这时要对k对len取模
如果取模之后得0,相当于不用rotate,直接返回
处理完特殊情况后,就用熟悉的faster/slower双指针解决就好(看到这种linkedlist,倒着数数的,就条件反射了)
先对faster设步长为n,然后faster和slower再一起走,知道faster.next==null,说明slower指向要倒着数的开始点的前一个位置。
所以slow.next就是要返回的newhead,保存一下。
然后把faster.next接到head上,slower.next存为null,作队尾。
这样就把list给rotate了。
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head==null||head.next==null||n==0)
return head;
ListNode fast = head, slow = head,countlen = head;
ListNode newhead = new ListNode(-1);
int len = 0;
while(countlen!=null){
len++;
countlen = countlen.next;
}
n = n%len;
if(n==0)
return head;
for(int i = 0; i < n; i++)
fast = fast.next;
while(fast.next!=null){
slow = slow.next;
fast = fast.next;
}
newhead = slow.next;
fast.next = head;
slow.next = null;
return newhead;
}
}
放一张AC通过的图
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个node,从那开始到结尾和之前那部分对调,那个例子就是,4->5拿前面来,1->2->3拿后面去。
几个特殊:
k是可以大于整个list的长度的,所以这时要对k对len取模
如果取模之后得0,相当于不用rotate,直接返回
处理完特殊情况后,就用熟悉的faster/slower双指针解决就好(看到这种linkedlist,倒着数数的,就条件反射了)
先对faster设步长为n,然后faster和slower再一起走,知道faster.next==null,说明slower指向要倒着数的开始点的前一个位置。
所以slow.next就是要返回的newhead,保存一下。
然后把faster.next接到head上,slower.next存为null,作队尾。
这样就把list给rotate了。
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head==null||head.next==null||n==0)
return head;
ListNode fast = head, slow = head,countlen = head;
ListNode newhead = new ListNode(-1);
int len = 0;
while(countlen!=null){
len++;
countlen = countlen.next;
}
n = n%len;
if(n==0)
return head;
for(int i = 0; i < n; i++)
fast = fast.next;
while(fast.next!=null){
slow = slow.next;
fast = fast.next;
}
newhead = slow.next;
fast.next = head;
slow.next = null;
return newhead;
}
}
放一张AC通过的图
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【061-Rotate List(旋转单链表)】
- leetcode:Rotate List 【Java】
- [leetcode]61. Rotate List@Java解题报告
- Java for LeetCode 061 Rotate List
- leetcode解题61. Rotate List java版(旋转链表)
- (java)leetcode-61:Rotate List
- 【leetcode】61. Rotate List【java】
- [Leetcode] Rotate List (Java)
- LeetCode 61 — Rotate List(C++ Java Python)
- Rotate List leetcode java
- leetcode JAVA Rotate List 难度系数3 3.20
- Rotate List leetcode
- 【小熊刷题】Reverse Linked List <Leetcode 206, Java>
- Leetcode 61. Rotate List
- [LeetCode] Rotate List
- LeetCode解题报告—— Rotate List & Set Matrix Zeroes & Sort Colors
- LeetCode -- Rotate List
- 景岁的Leetcode解题报告:147.Insertion Sort List (Java)
- 【LeetCode-面试算法经典-Java实现】【142-Linked List Cycle II(单链表中有环II)】
- leetcode - Rotate List