题目要求:
分析:
这道题目包含链表反转,所以可以调用反转链表那道题目。传送门:反转链表
既然知道如何反转链表,那么只需要对整个链表根据k来进行断开即可。
断开之后,调用反转链表方法,再将后面的接上,如此循环,直到最后。
在这里,要注意的一点有:如果节点总数不为k的整数倍,则保持原有顺序。
具体思路如下图:
具体代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next == null)
return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode node1 = dummy;
ListNode node2 = dummy;
while(node2.next != null) {
for(int i = 0; i < k; i++) {
if(node2 == null)
break;
node2 = node2.next;
}
if(node2 == null)
break;
ListNode start = node1.next;
ListNode nextRegion = node2.next;
node2.next = null;
node1.next = reverseList(start);
start.next = nextRegion;
node1 = start;
node2 = node1;
}
return dummy.next;
}
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode pre = null;
ListNode curr = head;
ListNode temp = new ListNode(0);
while(curr != null) {
temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}
return pre;
}
}