法1:快慢指针
Python
参考:灵茶山艾府
# 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]:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
Java
class Solution {
public ListNode middleNode(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy, slow = dummy;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow.next;
}
}
博客围绕链表的中间结点问题展开,介绍了使用快慢指针的解法,还给出了Python和Java两种语言的实现参考,参考来源为灵茶山艾府。
1281

被折叠的 条评论
为什么被折叠?



