LeetCode-3.23-876-E-链表的中间结点(Middle of the Linked List)


给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。

Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.

示例 1:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。

思路

(1)刚开始想的是奇偶个数不同造成node1.next.next是空值,没法继续;
(2)其实node1.next.next是空值也没关系,为null就可以了;故有解法1-2的写法;
(3)解法1-2中需要注意的是while(node1 != null && node1.next != null){}node1 != null保证了不会执行null.next这句

解法1-双指针

在这里插入图片描述

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode node1 = head;
        ListNode node2 = head;
        while(node1.next != null){
            if(node1.next.next == null){
                node1 = node1.next;
            }else{
                node1 = node1.next.next;
            }
            node2 = node2.next;
        }
        return node2;

    }
}

解法1-2

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode node1 = head;
        ListNode node2 = head;
        while(node1 != null && node1.next != null){
            // if(node1.next.next == null){
            //     node1 = node1.next;
            // }else{
            //     node1 = node1.next.next;
            // }
            node1 = node1.next.next;
            node2 = node2.next;
        }
        return node2;
    }
}

解法1-3

(1)链表长度为1时,直接返回slow;
(2)链表长度为2时,slow指向第2个元素,并返回;

2020/4/8

在这里插入图片描述

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        
        return slow;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值