eolymp
bolt
Try our new interface for solving problems
Problems

LinkedList Middle

LinkedList Middle

Given a linked list, find its middle element.

Definition of a single linked list:

// Java
class ListNode {
  int val;
  ListNode next;
  ListNode(int x) {
    val = x;
    next = null;
  }
}
// C++
class ListNode
{
public:
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};
// C
struct ListNode
{
  int val;
  struct ListNode *next;
};

Implement a function MiddleElement that returns a pointer to the middle node. If linked list contains n elements, its middle element has index number ceil(n / 2).

// Java
ListNode MiddleElement(ListNode head)
// C, C++
ListNode* MiddleElement(ListNode *head)

Example

prb10380.gif

The length of the list n = 5 is odd. Function MiddleElement must return a pointer to the node with value 3 (middle element).

prb10380_1.gif

The length of the list n = 4 is even. Function MiddleElement must return a pointer to the node with value 2 (middle element).

Time limit 1 second
Memory limit 128 MiB
Author Michael Medvediev