题目
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
分析
快慢指针,两倍速差
C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* middleNode(struct ListNode* head) {
struct ListNode *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL)
{
slow = (slow->next);
fast = (fast->next->next);
}
return slow;
}
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast = slow =head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
总结
c 语言中空是NULL ,python中是None return false即可