链表系列一>重排链表

题目: 链接: link这里是引用解析: 在这里插入图片描述细节: 在这里插入图片描述代码:代码语言:javascript代码运行次数:0运行复制*** Definition for singly-linked list.* public

链表系列一>重排链表

题目:

链接: link

这里是引用

解析:

在这里插入图片描述

细节:

在这里插入图片描述

代码:

代码语言:javascript代码运行次数:0运行复制
/**
 * 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 void reorderList(ListNode head) {
        //边界
        if (head == null || head.next == null || head.next.next == null) return;

        ListNode fast = head,slow = head;

        //1.找链表的中间节点
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        
        //2.把 slow 后面的部分链表给逆序 - 头插法
        ListNode prev = new ListNode(0);
        ListNode cur = slow.next;
        slow.next = null;//把两个链表断开

        while(cur != null){
            //记录cur后的节点,不然后面就断开了
            ListNode next = cur.next;
            cur.next = prev.next;
            prev.next = cur;
            cur = next;
        }

        //3.合并两个链表(第一个头--》head, 第二个的头--》prev)
        ListNode tmp = new ListNode(0);
        ListNode cur1 = head,cur2 = prev.next;
        ListNode curN = tmp;

        while(cur1 != null){
            curN.next = cur1;
            curN = cur1;
            cur1 = cur1.next;

            if(cur2 != null){
                curN.next = cur2;
                curN = cur2;
                cur2 = cur2.next;
            }
        
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-04-27,如有侵权请联系 cloudcommunity@tencent 删除public链表classintnull

发布者:admin,转转请注明出处:http://www.yc00.com/web/1747488105a4645863.html

相关推荐

  • 链表系列一>重排链表

    题目: 链接: link这里是引用解析: 在这里插入图片描述细节: 在这里插入图片描述代码:代码语言:javascript代码运行次数:0运行复制*** Definition for singly-linked list.* public

    22小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信