-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob_19.py
67 lines (58 loc) · 1.48 KB
/
prob_19.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 19. Remove Nth Node From End of List
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# solution 0: not super clean, need to make dummy node to make this clean
class Solution_2(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head.next:
return None
if not head:
return head
# init 2 pointers
l = head
e = head
for _ in range(n):
e = e.next
if not e:
return head.next
while e.next:
l = l.next
e = e.next
if l.next:
l.next = l.next.next
else:
return None
return head
# much cleaner with dummy node
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
# if not head.next:
# return None
# if not head:
# return head
# init 3 pointer
l = dummy
e = dummy
for _ in range(n+1):
e = e.next
while e:
l = l.next
e = e.next
l.next = l.next.next
return dummy.next