zoukankan      html  css  js  c++  java
  • 各种求链表中间节点


    /**
    * 各种求链表中间节点
    */
    public class FindMidNode {

    /**
    * 输入链表头结点,奇数长度返回中点,偶数长度返回上中点
    *
    * @param head 头结点
    * @return 中点或者上中点
    */
    public Node midOrUpMidNode(Node head) {
    if (head == null || head.next == null || head.next.next == null) {
    return head;
    }
    Node slow = head.next;
    Node fast = head.next.next;
    while (fast.next != null && fast.next.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    }
    return slow;
    }

    /**
    * 输入链表头结点,奇数长度返回中点,偶数长度返回下中点
    *
    * @param head 头结点
    * @return 中点或者下中点
    */
    public Node midOrDownMidNode(Node head) {
    if (head == null || head.next == null) {
    return head;
    }
    Node slow = head.next;
    Node fast = head.next;
    while (fast.next != null && fast.next.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    }
    return slow;
    }

    /**
    * 输入链表头结点,奇数长度返回中点前一个,偶数长度返回上中点前一个
    *
    * @param head 头结点
    * @return 结点
    */
    public Node midOrUpMidPreNode(Node head) {
    if (head == null || head.next == null || head.next.next == null) {
    return null;
    }
    Node slow = head;
    Node fast = head.next.next;
    while (fast.next != null && fast.next.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    }
    return slow;
    }

    /**
    * 输入链表头结点,奇数长度返回中点前一个,偶数长度返回下中点前一个
    *
    * @param head 头结点
    * @return 结点
    */
    public Node midOrDownMidPreNode(Node head) {
    if (head == null || head.next == null) {
    return null;
    }
    if (head.next.next == null) {
    return head;
    }
    Node slow = head;
    Node fast = head.next;
    while (fast.next != null && fast.next.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    }
    return slow;
    }

    /**
    * 链表结构
    */
    public static class Node {

    public int value;

    public Node next;

    public Node(int value) {
    this.value = value;
    }

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    pyenv
    [20200724NOIP提高组模拟T3]终章-剑之魂
    [20200724NOIP提高组模拟T2]圣章-精灵使的魔法语
    [20200724NOIP提高组模拟T1]序章-弗兰德的秘密
    [20200723NOIP提高组模拟T1]同余
    [SDOI2008]仪仗队
    P3195 [HNOI2008]玩具装箱
    [20200722NOIP提高组模拟T4]词韵
    [20200721NOIP提高组模拟T3]最小代价
    [20200721NOIP提高组模拟T1]矩阵
  • 原文地址:https://www.cnblogs.com/laydown/p/12837807.html
Copyright © 2011-2022 走看看