这个题目很自然的我就直接想到了模拟
随即出现了下面的代码
/**
* 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) {
ListNode dummy =new ListNode(-1);
dummy.next=head;
ListNode current =head;
ListNode old =head;
int length=0;
while(current.next!=null)
{
current=current.next;
length++;
}
current=head.next;
for(int i=0;i<length/k;i++)
{
for(int j=0;j<k-1;j++)
{
ListNode will=current.next;
current.next=old;
if(i==0)
dummy=current;
current=will;
}
old=current;
current=current.next;
}
return dummy;
}
}
反复检查发现第一个大循环到第二次大循环的连接没有连接上,没有什么很好的方案
/**
* 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) {
ListNode current =head;
ListNode old =head;
ListNode head1,head2,dummy;
ListNode tail1,tail2,temp;
dummy.next=head;
int length=0;
while(current.next!=null)
{
current=current.next;
length++;
}
current=head.next;
for(int i=0;i<length/k;i++)
{
for(int j=0;j<k-1;j++)
{
ListNode nextnode=current.next;
current.next=old;
old=current;
current=nextnode;
}
if(i==0)
{
head1=old;
tail1=head;
dummy=head1;
old=current;
temp=old;
current=current.next;
}
else
{
head2=old;
tail2=temp;
tail1.next=head2;
head1=head2;
tail1=tail2;
old=current;
temp=old;
current=current.next;
}
}
tail2.next=current;
return dummy;
}
}
好吧还是有问题
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k == 1) {
return head; // 如果链表为空或者k为1,不需要反转,直接返回原链表
}
ListNode dummy = new ListNode(0); // 初始化dummy节点
dummy.next = head;
ListNode current = dummy, next = dummy, prev = dummy;
int length = 0;
// 计算链表的长度
while (current.next != null) {
current = current.next;
length++;
}
// 按组反转链表
while (length >= k) {
current = prev.next; // 当前组的第一个节点
next = current.next; // 当前组的第二个节点
// 反转当前组内的节点
for (int i = 1; i < k; i++) {
current.next = next.next;
next.next = prev.next;
prev.next = next;
next = current.next;
}
// 移动 prev 到当前组的末尾
prev = current;
length -= k;
}
return dummy.next;
}
}
很蠢