반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 19 | Remove Nth Node From End of List | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
문제
Given the head of a linked list, remove the nth node from the end of the list and return its head.
조건
- The number of nodes in the list is sz.
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
내 풀이
list의 길이(length)를 잰다.
length와 n이 같다면 맨 앞의 노드를 지워야하는 것이므로 head.next를 리턴한다.
그 외의 경우에는 끝에서 n+1번째 노드까지 찾아간 후, head.next = head.next.next를 한다.(이때 head는 끝에서 n+1번째다)
코드
# 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]:
length = 1
nhead = head
thead = head
while thead.next:
thead = thead.next
length += 1
if length == n:
return head.next
nth = length - n - 1
while nth > 0:
nhead = nhead.next
nth -= 1
nhead.next = nhead.next.next
return head
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 112 | Path Sum | Python (0) | 2022.10.04 |
---|---|
[LeetCode] 658 | Find K Closest Elements | Python (2) | 2022.09.29 |
[LeetCode] 838 | Push Dominoes | Python (0) | 2022.09.27 |
[LeetCode] 990 | Satisfiability of Equality Equations | Python (0) | 2022.09.26 |
[LeetCode] 1680 | Concatenation of Consecutive Binary Numbers | Python (0) | 2022.09.23 |
Comments