반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[2095] Delete the Middle Node of a Linked List | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/
문제
You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.
The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.
- For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.
조건
- The number of nodes in the list is in the range [$1, 10^5$].
- 1 <= Node.val <= $10^5$
내 풀이
list를 앞부터 뒤까지 쭉 훑으며 list의 길이를 잰다.
list 길이의 절반이 되는 지점을 없앤다.
코드
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
length = 1
nhead = head
while nhead.next:
length += 1
nhead = nhead.next
if length == 1:
return None
elif length == 2:
head.next = None
nhead = head
half = 1
while nhead.next:
half += 1
if half == length//2+1:
nhead.next = nhead.next.next
break
nhead = nhead.next
return head
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCOde] 692 | Top K Frequent Words | Python (0) | 2022.10.19 |
---|---|
[LeetCode] 38 | Count and Say | Python (0) | 2022.10.18 |
[LeetCode] 237 | Delete Node in a Linked List | Python (0) | 2022.10.13 |
[LeetCode] 976 | Largest Perimeter Triangle | Python (0) | 2022.10.12 |
[LeetCode] 334 | Increasing Triplet Subsequence | Python (0) | 2022.10.11 |
Comments