Middle of Linked List (ladder)

Description

Find the middle node of a linked list.

Example:
Given 1->2->3, return the node with value 2.
Given 1->2, return the node with value 1.

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
    /**
    * Definition of ListNode
    * class ListNode {
    * public:
    *     int val;
    *     ListNode *next;
    *     ListNode(int val) {
    *         this->val = val;
    *         this->next = NULL;
    *     }
    * }
    */
    class Solution{
    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) {
             return nullptr;
         }
         ListNode* slow = head;
         ListNode* fast = head->next;
         while (fast && fast->next) {
             slow = slow->next;
             fast = fast->next->next;
         }
         return slow;
     }
    };
    

Similar problems

x

Tags

x

results matching ""

    No results matching ""