算法刷题-Day05

1. 链表的中间节点

题目描述

给定一个头结点为 head 的非空单链表,返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。

输入示例

输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.

思路讲解和代码实现

package com.why.day05;

/**
 * @ClassName:GetNode
 * @Description:todo 链表的中间结点
 * @Author: why
 * @DateTime:2021/11/2 17:03
 */
public class GetNode {
    /**
     * 返回链表的中间结点
     *
     * 思路:
     *  1. 统计链表长度length
     *  2. 定位到链表中间结点的位置
     * @param head
     * @return
     */
    public static ListNode middleNode(ListNode head) {
        ListNode temp = head;
        int length = 0;
        while (temp != null){
            length ++;
            temp = temp.next;
        }

        ListNode midNode = head;
        if ( length%2 == 0){
            int count = length / 2 + 1;
            for (int i = 1; i < count; i++) {
                midNode = midNode.next;
            }
            return midNode;
        }else {
            double count = length / 2 + 0.5;
            for (int i = 1; i < count; i++) {
                midNode = midNode.next;
            }
            return midNode;
        }
    }
}

class ListNode{
    int val;
    ListNode next;
}

2. 删除链表倒数第n个结点

题目描述

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

输入示例

image-20211102173022239

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

思路讲解和代码实现

package com.why.day05;

/**
 * @ClassName:DeleteNode
 * @Description:todo 删除链表的倒数第n个结点
 * @Author: why
 * @DateTime:2021/11/2 17:31
 */
public class DeleteNode {

    /**
     * 删除链表的倒数第n个结点
     *
     * 思路:
     *  1. 创建pre和after指针指向链表的首部
     *  2. 遍历链表,移动pre指针指向链表元素,并动态的记录length
     *  3. 当length >= n+1时after指针开始移动
     *  4. 当链表遍历完成时after指向的结点即为删除的前一结点
     *  5. 删除结点
     *  6. 返回头结点
     * @param head
     * @param n
     * @return
     */
    public static ListNode removeNthFromEnd(ListNode head, int n) {

        /**
         * 只有一个结点返回null
         */
        if (head.next == null && n == 1){
            return null;
        }

        ListNode pre = head;
        ListNode after = null;
        int length = 1;

        while (pre.next != null){
            pre = pre.next;
            length += 1;
            if (length >= n + 1){
                if (length == n+1){
                    after = head;
                }else {
                    after = after.next;
                }
            }
        }


        if (after == head){
            after.next = head.next.next;
        }else if (after == null){ //删除的结点是头节点的情况
            head = head.next;
        } else{
            //删除结点
            after.next = after.next.next;
        }
        return head;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值