LinkedList Middle#10380

LinkedList Middle

1 second
128 megabytes
Very easy

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 elements, its middle element has index number .

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

Input

The function receives a pointer head to the head of the linked list.

Output

The function should return a pointer to the middle element of the list.

Note

prb10380.gif

The length of the list n = 5 is odd. Function MiddleElement must return a pointer to the node with value (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 (middle element).