[leetcode]19. Remove Nth Node From End of List
链表题没法在本地打断点调试真的烦。。。不过好在这题简单
注意考虑要去除的元素在正数第一位的情况就好。
Runtime: 40 ms, faster than 88.15% of Python3 online submissions forRemove Nth Node From End of List.
Memory Usage: 13.1 MB, less than 64.23% of Python3 online submissions for Remove Nth Node From End of List.
Submission Detail
208 / 208 test cases passed.
|
Status:
Accepted |
Runtime: 40 ms
Memory Usage: 13.1 MB
|
Submitted: 1 minute ago
|
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: listval =[] temp = head ret = head while(temp.next != None): listval.append(temp.val) temp = temp.next #lastone listval.append(head.val) lengthS = len(listval) #0 if lengthS == 0: return head #1 if lengthS == 1: return [] #normal reverse_n = lengthS+1 -n #reverse_n == 1 if reverse_n ==1: return head.next for index in range(1,reverse_n): if index+1 == reverse_n: head.next = (head.next).next else: head = head.next return ret
16ms:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: cur = head for i in range(n): cur = cur.next if not cur: head = head.next return head else: pre = head cur = pre.next while cur: for i in range(n): cur = cur.next if not cur: pre.next = pre.next.next return head else: pre = pre.next cur = pre.next