876. Middle of the Linked List
题目描述:
Given a non-empty, singly linked list with head node head
, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
Note:
- The number of nodes in the given list will be between
1
and100
.
解题思路:
寻找链表的中间节点,首先看看中间节点有什么特点,中间节点的到头节点的节点数等于尾节点到中间节点的节点数,或者比尾节点到中间节点的节点数多一。
此时可以申明两个节点指向头结点,一个快节点每步走两个节点,一个慢节点每步走一个节点,当快捷点为NULL或快捷点的next节点为NULL时,慢节点指向中间节点。
代码:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* middleNode(ListNode* head) { 12 if (head == NULL) 13 return head; 14 ListNode* fast = head; 15 ListNode* slow = head; 16 while (fast != NULL && fast->next != NULL) { 17 fast = fast->next; 18 fast = fast->next; 19 slow = slow->next; 20 } 21 return slow; 22 } 23 };