/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ classSolution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNodedummy=newListNode(0); dummy.next = head; ListNodefast= dummy; ListNodeslow= dummy; for (inti=0; i <= n; i++) { fast = fast.next; } while (fast != null) { slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return dummy.next; } }
结果
执行用时 : 0 ms, 击败 100.00% 使用 Java 的用户
内存消耗 : 40.65 MB, 击败 7.23% 使用 Java 的用户
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution(object): defremoveNthFromEnd(self, head, n): dummy = ListNode(0) dummy.next = head fast = slow = dummy for i inrange(n + 1): fast = fast.next while fast != None: slow = slow.next fast = fast.next slow.next = slow.next.next return dummy.next
结果
执行用时 : 24 ms, 击败 29.15% 使用 Python 的用户
内存消耗 : 13.18 MB, 击败 7.92% 使用 Python 的用户
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defremoveNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: dummy = ListNode(0) dummy.next = head fast = slow = dummy for i inrange(n + 1): fast = fast.next while fast: slow = slow.next fast = fast.next slow.next = slow.next.next return dummy.next
/** * Definition for singly-linked list. * class ListNode(_x: Int = 0, _next: ListNode = null) { * var next: ListNode = _next * var x: Int = _x * } */ objectSolution{ defremoveNthFromEnd(head: ListNode, n: Int): ListNode = { val dummy = newListNode() dummy.next = head var fast = dummy var slow = dummy for (i <- 0 to n) { fast = fast.next } while (fast != null) { slow = slow.next fast = fast.next } slow.next = slow.next.next dummy.next } }