反转链表进阶版
题目
https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
代码
/**
* 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 first=new ListNode(0);//作为假的头节点
first.next=head;//指向头节点
ListNode pre=first;
while(head!=null){
ListNode tail=pre;
//长度是否不足k
for(int i=0;i<k;i++){
tail=tail.next;
if(tail==null){//长度不足k,不用翻转这组,直接返回结果;
return first.next;
}
}
ListNode next=tail.next; //记录这组结束的后一个节点
ListNode[] re=rev(head,tail);//反转这组链表
//将反转后的这组链表拼到原链表上
pre.next=re[0];//原tail
re[1].next=next;//原head
pre=re[1];
head=re[1].next;
}
return first.next;//first永远指向最新的头节点
}
//翻转链表
public ListNode[] rev(ListNode head,ListNode tail){
ListNode t1=head;
ListNode pre=tail.next;//本组的head要放在本组的最后一个,本组原tail.next成为原head的next
//以往反转链表是不写的,因为链表尾部后面没有节点了,这里因为后面还有所以写
ListNode next;
while(pre!=tail){
next=t1.next;
t1.next=pre;
pre=t1;
t1=next;
}
return new ListNode[]{tail,head};
}
}
拓展:不足k个的部分也反转
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode first=new ListNode(0);//作为假的头节点
first.next=head;//指向头节点
ListNode pre=first;
while(head!=null){
ListNode tail=pre;
for(int i=0;i<k;i++){
tail=tail.next;
if(tail.next==null){ //!!!改动点
break;
}
}
ListNode next=tail.next; //记录这组结束的后一个节点
ListNode[] re=rev(head,tail);//反转这组链表
//将反转后的这组链表拼到原链表上
pre.next=re[0];//原tail
re[1].next=next;//原head
pre=re[1];
head=re[1].next;
}
return first.next;//first永远指向最新的头节点
}
//翻转链表
public ListNode[] rev(ListNode head,ListNode tail){
ListNode t1=head;
ListNode pre=tail.next;//本组的head要放在本组的最后一个,本组原tail.next成为原head的next
//以往反转链表是不写的,因为链表尾部后面没有节点了,这里因为后面还有所以写
ListNode next;
while(pre!=tail){
next=t1.next;
t1.next=pre;
pre=t1;
t1=next;
}
return new ListNode[]{tail,head};
}
}
2024刷题
写的一坨,终于过了
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head.next==null) return head;//只有一个结点不必反转
ListNode dumb=new ListNode(0,head);//作为假的头节点
return reverse(dumb,head,k)[1];
}
//ans[0]:原来的头现在的尾,ans[1]现在的头
public ListNode[] reverse(ListNode before,ListNode head,int k){
ListNode[] ans=new ListNode[2];
int count=0;
if(head==null)
return ans;
//不足k个不反转-开始
int len=1;//计算长度
ListNode lennode=head;
while(lennode.next!=null){
len++;
lennode=lennode.next;
}
if(len<k){
ans[1]=head;
ans[0]=lennode;
before.next=head;
return ans;
}
//不足k个不反转-结束
//如果不足k个也要反转,则删除此段代码
//在反转本段前,先记录下一段的起点
ListNode next=head;
for(int i=0;i<k&&next!=null;i++){
next=next.next;
}
//反转链表
ListNode pre=null;
ListNode cur=head;
while(cur!=null&&count<k){
count++;
ListNode tmp=cur.next;//原来的next=后面的节点
cur.next=pre;
pre=cur;
cur=tmp;
}
ans[1]=pre;
before.next=pre;
//将前一个节点指向现在的头节点
ans[0]=reverse(head,next,k)[0];
return ans;
}
}