题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*;
/*
- public class ListNode {
- int val;
- ListNode next = null;
- } */
public class Solution { /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode reverseKGroup (ListNode head, int k) { // write code here if (head == null) { return head; } ListNode newHead = new ListNode(-1); newHead.next = head; head = newHead;
ListNode pre = head; ListNode post = head; while (post != null) { int i = 0; while (i < k) { post = post.next; if (post == null) { return head.next; } i++; } ListNode node = pre.next; ListNode tmp = node; int j = 1; while (j <= k) { ListNode t = node.next; node.next = pre.next; pre.next = node; node = t; j++; } tmp.next = node; pre = tmp; post = pre; } return head.next; }
}
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if (head == null) {
return head;
}
ListNode newHead = new ListNode(-1);
newHead.next = head;
head = newHead;
ListNode pre = head;
ListNode post = head;
while (post != null) {
int i = 0;
while (i < k) {
post = post.next;
if (post == null) {
return head.next;
}
i++;
}
ListNode node = pre.next;
ListNode tmp = node;
int j = 1;
while (j <= k) {
ListNode t = node.next;
node.next = pre.next;
pre.next = node;
node = t;
j++;
}
tmp.next = node;
pre = tmp;
post = pre;
}
return head.next;
}
}