题目描述
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.
题意:给一个链表,返回中间节点,如果有两个中间节点,那么返回后面的那个。
样例
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.
算法1
题解:典型的快慢指针做法。慢指针一次走一个,快指针一次走两个,快指针走到链表尾部的时候,慢指针所在位置就是答案。
C++ 代码
ListNode* middleNode(ListNode* head) {
ListNode* slow = head;
ListNode* quick = head;
while(quick !=NULL && quick->next != NULL)
{
slow = slow->next;
quick = quick->next->next;
}
return slow;
}
如果题目要求返回靠前的那个,可以设置一个虚拟头节点,让快慢指针同时从虚拟节点出发。
ListNode* middleNode(ListNode* head) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* slow = dummy;
ListNode* quick = dummy;
while(quick !=NULL && quick->next != NULL)
{
slow = slow->next;
quick = quick->next->next;
}
return slow;
}
建议虚拟头结点用局部变量即可,new出来的还要考虑内存释放,才完美~~
嗯嗯 这点面试的时候建议加上。