zoukankan      html  css  js  c++  java
  • Lc879_链表的中间结点

    
    //给定一个带有头结点 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 之间。 
    // 
    // Related Topics 链表
    
    package leetcode.editor.cn;
    
    import com.example.demo.ArrayConvertLinkedList;
    import com.example.demo.ListNode;
    
    //Java:链表的中间结点
    public class P876MiddleOfTheLinkedList {
        public static void main(String[] args) {
            Solution solution = new P876MiddleOfTheLinkedList().new Solution();
            // TO TEST
            int[] array1 = {1,2,3,4,5};
            ListNode head1 = ArrayConvertLinkedList.arrayToNode(array1);
            ListNode res = solution.middleNode(head1);
            ArrayConvertLinkedList.printNode(res);
        }
        //leetcode submit region begin(Prohibit modification and deletion)
    
        /**
         * Definition for singly-linked list.
         * public class ListNode {
         * int val;
         * ListNode next;
         * ListNode(int x) { val = x; }
         * }
         */
        class Solution {
            public ListNode middleNode(ListNode head) {
                int len = 0;
                ListNode curr = head;
                while (curr != null) {
                    len++;
                    curr = curr.next;
                }
    
                int middle = len / 2 + 1;;
    
                ListNode curr1 = head;
                int currPosition = 1;
                while (curr1 != null) {
                    if (currPosition == middle) {
                        return curr1;
                    } else {
                        currPosition++;
                        curr1 = curr1.next;
                    }
                }
                return null;
            }
        }
    //leetcode submit region end(Prohibit modification and deletion)
    
    }
    
    
  • 相关阅读:
    键盘输入thisisunsafe
    vscode
    iterm2 rz sz
    homebrew镜像更换
    mac
    homebrew下载不成功
    shutil:高层文件操作
    tempfile:临时文件系统对象
    linecache:读取文本文件的指定内容
    fnmatch:Unix式glob模式匹配,简单场景下可以代替正则
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/13271798.html
Copyright © 2011-2022 走看看