美文网首页LeetCode
链表的中间结点

链表的中间结点

作者: 习惯了_就好 | 来源:发表于2019-07-15 17:45 被阅读0次

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

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

    示例 1:

    输入:[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.

    示例 2:

    输入:[1,2,3,4,5,6]
    输出:此列表中的结点 4 (序列化形式:[4,5,6])
    由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。

    提示:

    给定链表的结点数介于 1 和 100 之间。
    

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/middle-of-the-linked-list
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode middleNode(ListNode head) {
            if(head == null)return null;
            if(head.next == null) return head;
            
            List<ListNode> list = new ArrayList<>();
        
            while(head != null){
                list.add(head);
                head = head.next;
            }
            return list.get(list.size() / 2);
            
        }
    }
    
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode middleNode(ListNode head) {
            ListNode slow = head;
            ListNode fast = head;
            ListNode current = head;
            int count = 0;
            while(current != null){
                count++;
                current = current.next; 
            }
            
            
            while(fast != null && fast.next != null && fast.next.next != null){
                slow = slow.next;
                fast = fast.next.next;
            }
            
            return count % 2 == 0 ? slow.next : slow;
        }
    }
    

    相关文章

      网友评论

        本文标题:链表的中间结点

        本文链接:https://www.haomeiwen.com/subject/xjzskctx.html