Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3a26161

Browse files
Update LinkedList reference in readme.md
1 parent 2620abd commit 3a26161

File tree

1 file changed

+39
-11
lines changed

1 file changed

+39
-11
lines changed
Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,42 @@
1+
'''
2+
Question: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
3+
Given the head of a linked list, remove the nth node from the end of the list and return its head.
4+
5+
=> => => =>
6+
7+
Input: head = [1,2,3,4,5], n = 2
8+
Output: [1,2,3,5]
9+
10+
Input: head = [1], n = 1
11+
Output: []
12+
13+
Input: head = [1,2], n = 1
14+
Output: [1]
15+
16+
Follow up: Could you do this in one pass?
17+
18+
19+
'''
20+
121
# Definition for singly-linked list.
2-
# class ListNode:
3-
# def __init__(self, x):
4-
# self.val = x
5-
# self.next = None
22+
class ListNode:
23+
def __init__(self, val=0, next=None):
24+
self.val = val
25+
self.next = next
626

727
class Solution:
8-
def deleteNode(self, node):
9-
"""
10-
:type node: ListNode
11-
:rtype: void Do not return anything, modify node in-place instead.
12-
"""
13-
node.val = node.next.val
14-
node.next = node.next.next
28+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
29+
dummy = ListNode(0, head)
30+
left = dummy
31+
right = head
32+
while n > 0 and right:
33+
right = right.next
34+
n -= 1
35+
36+
while right:
37+
left = left.next
38+
right = right.next
39+
40+
# delete
41+
left.next = left.next.next
42+
return dummy.next

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /