Skip to content

Commit 695b581

Browse files
committed
add leetcode_19
1 parent 0ad910e commit 695b581

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

LeetCode/LeetCode_19.py

+20-3
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ def __init__(self, x):
66

77
class Solution:
88
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
9-
# fast = slow = head
9+
# fast ,slow =head, head
1010
# if n == 1 and not head.next:
1111
# # print(n)
1212
# return []
@@ -22,5 +22,22 @@ def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
2222
# return None
2323
# slow.next = slow.next.next
2424
# return head
25-
26-
# Solution().removeNthFromEnd([1, 2], 1)
25+
if n == 1 and not head.next:
26+
return None
27+
fast, slow = head, head
28+
while n and fast:
29+
fast = fast.next
30+
n -= 1
31+
if not fast:
32+
return head.next
33+
while fast.next:
34+
slow = slow.next
35+
fast = fast.next
36+
temp = slow.next.next
37+
del slow.next
38+
slow.next = temp
39+
if __name__ == "__main__":
40+
head = ListNode(1)
41+
head.next=ListNode(2)
42+
Solution().removeNthFromEnd(head, 1)
43+
print(head.val)

0 commit comments

Comments
 (0)