LEETCODE | PYTHON | 876 | 链表的中间节点
1. 题目
给定一个头结点为 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/convert-binary-number-in-a-linked-list-to-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处
2. 代码 Ⅰ:暴力法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
#特殊情况判断
if head.next == None:
return head
#计算链表长度
l = 0
cur = head
while cur:
l = l + 1
cur = cur.next
#找到中间节点的位置
pos = l//2 + 1
#遍历找到中间节点并输出
index = 1
cur = head
while cur and index<pos:
index = index + 1
cur = cur.next
return cur
3. 代码 Ⅱ:快慢指针法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
#特殊情况判断
if head.next == None:
return head
#初始化设定快慢指针
fast = head
slow = head
#遍历判断:当快指针走到结尾时慢指针到达中间位置
while fast and fast.next:
fast = fast.next.next
slow = slow.next
return slow