解题思路
先遍历链表找出链表的的长度,并将每个节点加入到list集合中
判断需要多少次,每次取出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) {
int length=0;
ListNode temp = head;
List<ListNode> listNodes = new ArrayList<>();
while (temp!=null){
length++;
listNodes.add(temp);
temp=temp.next;
}
ListNode ans = new ListNode(0);
ListNode tail = ans;
int times = length/k;
int location = 0;
while (times!=0){
int index =location;
location+=k;
for (int i=location-1;i>=index;i--){
ListNode headNode = listNodes.get(i);
ListNode node = new ListNode(headNode.val);
tail.next=node;
tail=tail.next;
}
times--;
}
if (length%k!=0){
for (int i=location;i<listNodes.size();i++){
ListNode headNode = listNodes.get(i);
ListNode node = new ListNode(headNode.val);
tail.next=node;
tail=tail.next;
}
}
return ans.next;
}
}