美文网首页
228. Middle of Linked List

228. Middle of Linked List

作者: aammyytt | 来源:发表于2018-04-16 22:21 被阅读0次

    題目:
    Find the middle node of a linked list.

    代碼:

    public:
        /**
         * @param head: the head of linked list.
         * @return: a middle node of the linked list
         */
        ListNode *middleNode(ListNode *head) {
            // Write your code here
            if (head == NULL)
                return NULL;
            int cnt = 0;
            ListNode *p = head;
            while (p != NULL) {
                cnt ++;
                p = p->next;
            }
            
            cnt = (cnt + 1) / 2;
            while (head != NULL) {
                if (cnt == 1)
                    return head;
                cnt --;
                head = head->next;
            }
        }
    };
    
    

    相关文章

      网友评论

          本文标题:228. Middle of Linked List

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