leetcode 0025
说明
只是为了记录一下,不求多快,也不深究。
会简要描述思路,代码中不写注释。
如碰到不会做的用了别人代码会在博客中标出。
题目描述
思路
- 搞一个头结点,每K个节点向头结点和头结点的下一个节点插入;
- 插入完k个节点之后,更新头结点为最先插入的那个节点;
- 重复1,最后的不足K个节点插入两遍(倒序之后再倒序)。
/**
* 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) {
if(head == null || head.next == null || k<2) {
return head;
}
ListNode start = new ListNode(0);
ListNode start2 = start;
int count = 0;
ListNode tail = null;
ListNode temp = null;
boolean flag = true;
while(true) {
if(count<k) {
if(count == 0) {
tail = head;
}
temp = head.next;
head.next = start.next;
start.next = head;
head = temp;
if(head == null) {
if(count == k-1) {
break;
}else {
if(flag) {
count = 0;
head = start.next;
start.next = null;
flag = false;
}else {
break;
}
}
}
count++;
}else {
count = 0;
start = tail;
}
}
return start2.next;
}
}