在上一个题的基础上改动了一下,因为内存受限,所以每次都从头寻找指定的节点,并单独实现了一个函数。
可读性比较差,估计过几天就看不懂自己写的了。不知道别人有什么更好的办法。等有空的时候好好研究一下链表的操作。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode resultHead = new ListNode(0);
resultHead.next = head;
ListNode tempHead = new ListNode(-1);
tempHead.next = resultHead;
ListNode tempEnd = new ListNode(-1);
ListNode lastNode = getNextNode(tempHead, k + 1);
if (lastNode == null) {
return resultHead.next;
}
while (lastNode != null) {
ListNode theNextStart = lastNode.next;
tempEnd.next = lastNode;
ListNode firstNode = tempHead.next.next;
if (firstNode.next != null) {
tempHead.next.next = lastNode;
for (int j = k - 1; j > 0; --j) {
ListNode n = getNextNode(firstNode, j - 1);
tempEnd.next.next = n;
tempEnd.next = tempEnd.next.next;
}
tempHead.next = firstNode;
firstNode.next = theNextStart;
} else {
break;
}
lastNode = getNextNode(tempHead, k + 1);
}
return resultHead.next;
}
public ListNode getNextNode(ListNode head, int n) {
ListNode result = new ListNode(0);
result.next = head;
for (int i = 0; i < n; ++i) {
result.next = result.next.next;
if (result.next == null) {
return null;
}
}
return result.next;
}
}