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

    注意点: 找到某个节点,首先找到它的前一个节点!!!

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        // 找出中间节点。
        public int getmid(ListNode head){
            
            ListNode tmp = head;
            int len = 1;
            while( tmp.next != null ){
                tmp = tmp.next;
                len++;
            }
            if( len % 2 == 0 )
                len = len/2 + 1;
            else
                len = (len+1)/2;
            return len;
            
        }
        public ListNode middleNode(ListNode head) {
            
            
            int mid = getmid(head);
            ListNode node = head;
            // 第一个节点出发, 定位到mid节点的前一位。
            for( int i=1; i<mid; i++){
                node = node.next;
            }
            return node;
            
        }
  • 相关阅读:
    @bzoj
    @bzoj
    @codeforces
    @codeforces
    @bzoj
    @codeforces
    @codeforces
    @codeforces
    @NOIP2018
    反转字符串--C和Python
  • 原文地址:https://www.cnblogs.com/lijins/p/10147607.html
Copyright © 2011-2022 走看看