题目描述
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) {
if (head == null || head.next == null || k <= 1) {
return head;
}
int m = k - 1;
ListNode p0 = null, p1 = head, p2 = head;
while (p2 != null) {
if (m != 0) {
p2 = p2.next;
m--;
}
if (m == 0 && p2 != null) {
reverse(p1, p2);
if (p0 == null) {
head = p2;
} else {
p0.next = p2;
}
p0 = p1;
p1 = p1.next;
p2 = p1;
m = k - 1;
}
}
return head;
}
public void reverse(ListNode head, ListNode tail) {
ListNode p1 = head, p2 = head.next, p = head, last = tail.next;
while (p2 != last && p2 != null) {
p1.next = p2.next;
p2.next = p;
p = p2;
p2 = p1.next;
}
}
}
全部评论
(0) 回帖