주말 잘 쉬고 리트코드 하러 왔슴당.
오늘 리트코드는 Linked List를 이용하는 것이었다!
옛날에 리트코드 처음 했을 때 파이썬으로 linked list 문제 푸는 데 애를 먹었던 기억이 생생하다.
C로 linked list를 배운 나는 파이썬의 자료구조가 어색했다.
여튼! 오늘 문제는 linked list의 중간 원소를 찾아 그 원소로 시작하는 부분을 답하는 것이다.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
while cur and cur.next:
head = head.next
cur = cur.next.next
return head
cur과 cur.next가 none이 아닐 동안, head는 한칸씩, cur은 두칸씩 간다. 그렇게 되면 cur이 끝날 때 head는 len(cur)//2, 그러니까 우리가 원하는 중간 까지 가있는 것이다.
간단히 head를 리턴해주면 완성!
처음에 while문에서 cur을 빼고 cur.next만 했는데, 이렇게 되면 빈 리스트가 들어오는 경우 오류가 날 수 있다. 그래서 cur과 cur.next가 둘 다 존재한다는 것을 보장해야만 next나 next.next로 갈 수 있는 것이다!
오늘도 완료우!
앞으로 한걸음씩 성장해나가는 내가 되었으면 좋겠다.
'Leetcode' 카테고리의 다른 글
Leetcode 567. Permutation in String (0) | 2021.10.14 |
---|---|
Leetcode 3. Longest Substring Without Repeating Characters (0) | 2021.10.13 |
Leetcode 557. Reverse Words in a String III (0) | 2021.10.08 |
Leetcode 167. Two Sum II - Input array is sorted (0) | 2021.10.07 |
Leetcode 283. Move Zeroes (0) | 2021.10.06 |