三、链表--

链表由多个节点node连接而成;
每个节点里面有val 和 下一节点地址

node.next = node1 //代表改变node的连接方向

node.next = new ListNode(1); //代表在node后面新加一个val为一的节点

ListNode run = new ListNode(0, head); //代表新建一个节点val为0 节点后面与head连接

ListNode pre = new ListNode(-1);
ListNode cur = pre;//新建一个val为-1节点 cur也指向pre的头节点
//可以用cur移动 最后return pre.next  代表最终结果

例题:
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
在这里插入图片描述

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

解题:在这里插入图片描述代码:


public class leetcode_25 {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode run = new ListNode(0, head);
        ListNode pre = run;
        ListNode end = run;

        while (end.next != null) {
            for (int i = 0; i < k && end != null; i++) {
                end = end.next;
            }
            if (end == null) {
                break;
            }
            ListNode start = pre.next;
            ListNode bin = end.next;
            //定义null来截断链表
            end.next = null;
            //反转
            pre.next = reverse(start);
            //接上反转后的链
            start.next = bin;
            pre = start;
            end = pre;

        }


        return run.next;
    }

//定义反转的方法
    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值