K个一组翻转链表-leetcode
题目描述
给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
示例 2:

输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]
提示:
- 链表中的节点数目为
n 1 <= k <= n <= 50000 <= Node.val <= 1000
解法一
思路:
对于每个部分进行翻转,翻转后记录新的头尾节点,等所有的分组都翻转完毕后,根据之前记录的头尾节点将所有分组的链表进行连接。
代码:
/**
* 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 {
static List<ListNode> list=new ArrayList<>();
public ListNode reverseKGroup(ListNode head, int k) {
list.clear();
//记录当前轮的节点数
int countNode=0;
ListNode subHead = head;
ListNode subRear=head;
ListNode last=null;
boolean flag=false;
while (true) {
flag=false;
countNode=0;
while (subRear!=null) {
countNode++;
subRear=subRear.next;
if(countNode==k) {flag=true;break;}
}
if(flag)reverse(subHead,subRear);
else {
list.add(last);
break;
}
subHead=subRear;
last=subRear;
}
for(int i=1;i+1<list.size();i+=2) {
list.get(i).next=list.get(i+1);
}
return list.get(0);
}
public void reverse(ListNode head,ListNode rear) {
ListNode cur = null;
ListNode p=head;
ListNode q=p.next;
while (true) {
p.next=cur;
cur=p;
p=q;
if(p==rear) break;
q=q.next;
}
list.add(cur);
list.add(head);
}
}
解法二
思路:
增加一个空的头节点,记录pre和nex节点,对于中间的节点进行翻转,翻转结束后正常连接。



代码:
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode hair = new ListNode(0);
hair.next = head;
ListNode pre = hair;
while (head != null) {
ListNode tail = pre;
// 查看剩余部分长度是否大于等于 k
for (int i = 0; i < k; ++i) {
tail = tail.next;
if (tail == null) {
return hair.next;
}
}
ListNode nex = tail.next;
ListNode[] reverse = myReverse(head, tail);
head = reverse[0];
tail = reverse[1];
// 把子链表重新接回原链表
pre.next = head;
tail.next = nex;
pre = tail;
head = tail.next;
}
return hair.next;
}
public ListNode[] myReverse(ListNode head, ListNode tail) {
ListNode prev = tail.next;
ListNode p = head;
while (prev != tail) {
ListNode nex = p.next;
p.next = prev;
prev = p;
p = nex;
}
return new ListNode[]{tail, head};
}
}

浙公网安备 33010602011771号