C++
Java
Python
Python3
C
C#
JavaScript
Ruby
Swift
Go
Scala
Kotlin
Rust
PHP
TypeScript
Racket
Erlang
Elixir
Dart
monokai
ambiance
chaos
chrome
cloud9_day
cloud9_night
cloud9_night_low_color
clouds
clouds_midnight
cobalt
crimson_editor
dawn
dracula
dreamweaver
eclipse
github
github_dark
gob
gruvbox
gruvbox_dark_hard
gruvbox_light_hard
idle_fingers
iplastic
katzenmilch
kr_theme
kuroir
merbivore
merbivore_soft
mono_industrial
nord_dark
one_dark
pastel_on_dark
solarized_dark
solarized_light
sqlserver
terminal
textmate
tomorrow
tomorrow_night
tomorrow_night_blue
tomorrow_night_bright
tomorrow_night_eighties
twilight
vibrant_ink
xcode
上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteMiddle(ListNode* head) {
}
};
运行代码
提交
golang 解法, 执行用时: 220 ms, 内存消耗: 9.4 MB, 提交时间: 2022-12-07 18:04:06
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteMiddle(head *ListNode) *ListNode {
dummyHead := &ListNode{Next: head}
slow, fast := dummyHead, dummyHead
for fast.Next != nil && fast.Next.Next != nil {
slow = slow.Next
fast = fast.Next.Next
}
slow.Next = slow.Next.Next // 循环结束后 slow.Next 为待删除节点
return dummyHead.Next
}
golang 解法, 执行用时: 244 ms, 内存消耗: 9.5 MB, 提交时间: 2022-12-07 18:03:48
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteMiddle(head *ListNode) *ListNode {
dummyHead := &ListNode{Next: head}
pre, slow, fast := dummyHead, head, head
for fast != nil && fast.Next != nil {
pre = slow // pre 记录了 slow 的上一个结点
slow = slow.Next
fast = fast.Next.Next
}
pre.Next = slow.Next // 循环结束后 slow 为待删除节点
return dummyHead.Next
}
golang 解法, 执行用时: 268 ms, 内存消耗: 9.4 MB, 提交时间: 2022-12-07 18:03:14
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteMiddle(head *ListNode) *ListNode {
if head.Next == nil {
return head.Next
}
slow, fast, pre := head, head, &ListNode{}
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
pre = slow
slow = slow.Next
}
pre.Next = pre.Next.Next
return head
}
python3 解法, 执行用时: 1296 ms, 内存消耗: 56.7 MB, 提交时间: 2022-12-07 17:59:53
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next is None:
return None
slow, fast, pre = head, head, None
while fast and fast.next:
fast = fast.next.next
pre = slow
slow = slow.next
pre.next = pre.next.next
return head