알고리즘/LeetCode
LeetCode 풀기 - 19. Remove Nth Node From End of List
앤테바
2021. 11. 15. 07:54
반응형
19. Remove Nth Node From End of List
Remove Nth Node From End of List - LeetCode Discuss
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
문제)
솔루션1)
스택 자료구조를 사용한다.
모든 노드를 순회하면서 스택에 노드를 추가하고 n번 만큼 pop()수행해서 삭제 대상 노드를 찾는다.
# 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]:
node = head
stack = deque()
while node:
stack.append(node)
node = node.next
for i in range(n-1):
stack.pop()
target_node = stack[-1]
if len(stack) == 1:
head = target_node.next
else:
prev_target_node = stack[-2]
prev_target_node.next = target_node.next
return head
반응형