道阻且长,行则将至,走慢一点没关系,不|

Ac_c0mpany丶

园龄:3年7个月粉丝:6关注:3

2023-12-11 21:07阅读: 4评论: 0推荐: 0

[LeetCode Hot 100] LeetCode25. K个一组翻转链表

题目描述

思路:

  1. 判断链表中是否足够k个元素
  2. 再将这k个元素内部翻转一下
  3. 将前后端点连接的指针变化一下


方法一:

/**
 * 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(0, head);
        ListNode p = dummy;
        while(p != null) {
            ListNode q = p;
            // 判断后面是否有k个节点
            for (int i = 0; i < k && q != null; i ++) q = q.next;
            if (q == null) break;
            // 后面有k个节点
            ListNode a = p.next, b = a.next;
            // 翻转内部
            for (int i = 0; i < k - 1; i ++) {
                ListNode temp = b.next;
                b.next = a; 
                a = b;
                b = temp;
            }
            // 翻转外部
            ListNode c = p.next;
            p.next = a;
            c.next = b;
            p = c;
        }
        return dummy.next;
    }
}

本文作者:Ac_c0mpany丶

本文链接:https://www.cnblogs.com/keyongkang/p/17895554.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ac_c0mpany丶  阅读(4)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 You Are My Sunshine REOL
You Are My Sunshine - REOL
00:00 / 00:00
An audio error has occurred.

作曲 : Traditional

You are my sunshine

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away

The other night, dear,

When I lay sleeping

I dreamed I held you in my arms.

When I awoke, dear,

I was mistaken

So I hung my head and cried.

You are my sunshine,

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away.

You are my sunshine,

My only sunshine

You make me happy

When skies are gray.

You'll never know, dear

How much I love you

Please don't take my sunshine away

Please don't take my sunshine away.

Please don't take my sunshine away.