Middle of Linked List
题目:
Find the middle node of a linked list.
分析:
这题目没什么好说的,给个节点定义:
class ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), 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 == NULL || head->next == NULL) {
return head;
}
ListNode* slow = head;
ListNode* fast = head;
while (fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};