LeetCode第25题:K个一组反转链表

LeetCode第25题:K个一组反转链表

  • 题目:给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
  • 解法一:这个方法是自己做的错方法,我希望可以通过循环K次,每一次都把后以为加到head的前面。改了好长时间也没改对。。。。放弃。。。。
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null ){
            return head;
        }
         int count = k-1;
        ListNode startNode = head, stopNode = head;     
        while(stopNode.next!=null && count!=0){
            stopNode = stopNode.next;
            count--;
        }
        if(count!=0)        
            return head;
        ListNode next = head.next;
        ListNode headt = head;
        ListNode Lnext= next.next;
        for(int i=0;i<k-1;i++){
            Lnext = next.next;
            head.next=Lnext;
            next.next=headt;
            headt=next;
            next=Lnext;
        }
        head.next = reverseKGroup(Lnext,k);
        return next;
    }
}
  • 解法二:在链表转置的地方看了好几遍才转过来弯
public ListNode reverseKGroup(ListNode head, int k) {
    if(head==null)
        return head;

    int count = k-1;
    ListNode startNode = head, stopNode = head;     //待反转结点的第一个和最后一个
    while(stopNode.next!=null && count!=0){
        stopNode = stopNode.next;
        count--;
    }
    if(count!=0)        //不到K个结点直接返回
        return head;
    ListNode next = stopNode.next;      //保存最后一个待反转结点的下一个结点
    stopNode = reverse(startNode, stopNode);    //原来的最后一个结点变为头结点
    startNode.next = reverseKGroup(next, k);    //原来的第一个结点变为尾结点,递归处理剩余链表

    return stopNode;
}

ListNode reverse(ListNode startNode, ListNode stopNode){    //链表反转
    ListNode pre = null, cur = startNode, stop = stopNode.next;
    while(cur!=stop){
        ListNode temp = cur.next;
        cur.next = pre;
        pre = cur;
        cur = temp;
    }

    return pre;
}

作者:bzdgz
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/javashi-jian-ji-bai-100nei-cun-96-by-bzdgz/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值