We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent cdf821d commit c20cebbCopy full SHA for c20cebb
remove-nth-node-from-end-of-list/yyyyyyyyyKim.py
@@ -0,0 +1,29 @@
1
+# Definition for singly-linked list.
2
+# class ListNode:
3
+# def __init__(self, val=0, next=None):
4
+# self.val = val
5
+# self.next = next
6
+class Solution:
7
+ def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
8
+
9
+ # 투포인터
10
+ # 시간복잡도 O(n), 공간복잡도 O(1)
11
12
+ # 더미 노드 사용(head삭제되는경우대비)
13
+ dummy = ListNode(0, head)
14
+ slow, fast = dummy, dummy
15
16
+ # fast를 n칸 이동(slow와의 간격n으로 유지)
17
+ for _ in range(n):
18
+ fast = fast.next
19
20
+ # fast가 끝에 도달할때까지 slow와 한 칸씩 이동
21
+ while fast.next:
22
23
+ slow = slow.next
24
25
+ # slow.next = 삭제대상, 건너뛰고연결(삭제처리)
26
+ slow.next = slow.next.next
27
28
+ # 새로운 head 반환
29
+ return dummy.next
0 commit comments