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;
    }
}
发布了194 篇原创文章 · 获赞 20 · 访问量 7973

猜你喜欢

转载自blog.csdn.net/Xjheroin/article/details/105056759