https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
포인터를 두 개 둔다
두 개의 포인터를 n+1칸 간격으로 유지하면서 전진시키고
뒤쪽 포인터가 끝까지 가면
앞쪽 포인터를 이용해 뒤에서 n번째의 노드를 제거하면 된다.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
p = head
for i in range(n):
p = p.next
if not p:
return head.next
p = p.next
nprev = head
while p:
p = p.next
nprev = nprev.next
nprev.next = nprev.next.next
return head'코딩 테스트 및 알고리즘 > Grind 75 (Blind 75 Leetcode Questions)' 카테고리의 다른 글
| LinkedList : Swap Nodes in Pairs (0) | 2024.01.20 |
|---|---|
| LinkedList : Reverse Nodes in k-Group (0) | 2024.01.18 |
| LinkedList : LRU Cache ( Doubly Linked List with Two Dummy Nodes 구현 ) (0) | 2024.01.16 |
| LinkedList : LRU Cache (Doubly Linked List 해법) (0) | 2024.01.14 |
| LinkedList : LRU Cache (Singly Linked List 해법) (0) | 2024.01.14 |