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.
这道题,比较简单,记录链表中间的值,不过还是记录一下快慢指针的做法。
先是我的做法,效率还行。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
int length = 0;
for(ListNode *i = head; i!=NULL; i = i -> next)
length++;
ListNode * middle = head;
for (int i= 0;i<length/2;i++)
middle = middle -> next;
return middle;
}
};
就是比较规矩,先找出终点,再找出中间节点。
再附上快慢指针的做法。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *slow=head, *fast=head;
while(fast && fast->next){
slow = slow -> next;
fast = fast -> next -> next;
}
return slow;
}
};
快指针一次前进两个,慢指针一次前进一个,非常巧妙。所以当快指针到末尾的时候,慢指针到中间。