문제
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Remove Nth Node From End of List - LeetCode
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
코드
노드를 삭제하는 경우 3가지
- head 삭제
- 마지막 노드 삭제
- 중간 노드 삭제
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def calcul_length(self):
count = 0
while self:
count += 1
self = self.next
return count
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
node = head
current = node
# 연결리스트의 길이가 1이고, 지워야할 노드가 1번일 경우
if calcul_length(head) == 1 and n == 1:
head.val = ''
return head
count = calcul_length(head)-n
# 1번 노드를 지워야할 경우
if count == 0:
return head.next
# 그 이외 경우
else:
while count > 1:
if current.next:
current = current.next
count -= 1
else:
return current
current.next = current.next.next
return node
'⏳ 알고리즘 > python 알고리즘 문제 풀이' 카테고리의 다른 글
프로그래머스 - 숫자 문자열과 영단어( 2021 카카오 채용연계형 인턴십 ) (0) | 2021.10.31 |
---|---|
프로그래머스 - 로또의 최고 순위와 최저 순위( 2021 Dev-Matching ) (0) | 2021.10.31 |
프로그래머스 - LV3. 베스트앨범 (0) | 2021.06.15 |
프로그래머스 - [1차] 뉴스 클러스터링(카카오 2018 블라인드 채용) (0) | 2021.06.11 |
프로그래머스 - LV2. 예상 대진표(2017 팁스타운) (0) | 2021.06.11 |