Description
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
NOTE
- Only constant extra memory is allowed.
- You may not alter the values in the list’s nodes, only nodes itself may be changed.
Example
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
解题思路
和24一样,不能新建节点,只能移动已有节点
看了眼test,其实要求还是比较温和的,当最终节点数量不够k的时候不需要进行reverse
所以只要在循环刚开始的地方判断接下来有没有足够多的节点数就好
一开始傻傻的把每个节点都存下来了,然后和后插法一样每次都插到最后,因为要存节点,所以做了很多无用操作,16ms hhhhhhh details里面都几乎没有这个时间的容身之处
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode[] swap = new ListNode[k];
ListNode answer = new ListNode(0);
Boolean flag = false;
ListNode temp;
ListNode p = answer;
answer.next = head;
int i, j;
while(true){
ListNode test = answer;
for(i = 0; i < k; i++){
if(test.next == null){
flag = true;
break;
}
test = test.next;
}
if(flag)
break;
for(i = 0; i < k ; i++){
swap[i] = answer.next;
}
for(i = 0; i < k; i++){
for(j = 0; j < i; j++){
swap[i] = swap[i].next;
}
}
temp = answer.next;
for(i = 0; i < k; i++){
temp = temp.next;
}
swap[0].next = temp;
for(i = k - 1; i >= 0; i--){
answer.next = swap[i];
answer = answer.next;
}
}
return p.next;
}
}
正确操作应该比较像前插法,内嵌2次k循环(一次循环到需要插入的点,一次用前插插入)就好QuQ
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null){
return null;
}
ListNode pre = new ListNode(-1);
pre.next = head;
//ListNode tail = head;
ListNode tail = pre;
head = pre;
while(tail.next != null){
//tail = pre;
for(int i = 0; i < k; ++i){
if(tail.next == null){
return head.next;
}
tail = tail.next;
}
tail = pre.next;
for(int i = 0; i < k - 1; ++i){
ListNode tmp = tail.next;
tail.next = tmp.next;
tmp.next = pre.next;
pre.next = tmp;
}
pre = tail;
}
return head.next;
}
}