zoukankan      html  css  js  c++  java
  • 链表元素按奇偶聚集

    leetcode地址:

    https://leetcode.com/problems/odd-even-linked-list/description/

    描述:

    Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

    You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

    Example 1:

    Input: 1->2->3->4->5->NULL
    Output: 1->3->5->2->4->NULL
    

    Example 2:

    Input: 2->1->3->5->6->4->7->NULL
    Output: 2->3->6->7->1->5->4->NULL
    

    Note:

    • The relative order inside both the even and odd groups should remain as it was in the input.
    • The first node is considered odd, the second node even and so on ...

    分析:

    这题感觉没什么难度,唯一有点难度的地方在于你最好不要创建新的节点,而仅仅是改变节点之间的连接关系,即只通过改变节点的next指针来重建链表顺序,这样才能达到空间复杂度为O(1)的要求。这题有两种,一种要求按照元素的下标的奇偶性进行排序,另一种按照节点的val值的奇偶性进行重排,区别不大,无非是对奇偶性的判断略有区别。

    我这里仍然使用了虚拟头结点来减小代码实现的复杂性。

    代码:

    public boolean isPalindrome(ListNode head) {
    if (null == head) {
    return true;
    }
    // 切分链表
    ListNode fast = head, slow = head;
    while (fast.next != null && fast.next.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    }
    ListNode right = slow.next;
    slow.next = null;
    right = reverse(right);
    while (right != null && head != null) {
    if (right.val != head.val) {
    return false;
    }
    right = right.next;
    head = head.next;
    }
    return true;
    }

    public ListNode reverse(ListNode list) {
    ListNode newHead = null;
    while (list != null) {
    ListNode next=list.next;
    list.next = newHead;
    newHead = list;
    list = next;
    }
    return newHead;
    }
  • 相关阅读:
    js 多媒体文件(图片,表格 等) 下载方法
    CentOS7 + asp.net core 3.1 + mysql 8 配置备忘
    项目管理平台参考设计
    golang 使用rate实现redis qps令牌桶限流
    golang执行命令实时输出(协程通过channel更新数据到主进程)
    go-chart go后端生成图表base64
    go-chart go后端生成图表base64
    golang OOM分析
    Golang xorm time自定义解析
    python 多线程
  • 原文地址:https://www.cnblogs.com/zhuge134/p/10927311.html
Copyright © 2011-2022 走看看