본문 바로가기
💻 LEETCODE

[LEETCODE] 876. Middle of The Linked List

by 구라미 2022. 11. 22.

 

876. Middle of The Linked List

Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.

Example 1:

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

 

Constraints:

  • The number of nodes in the list is in the range [1, 100].
  • 1 <= Node.val <= 100

 

내 풀이

# 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]:
        count = 1
        list = []
        temp = head.next
        while (temp):
            count += 1
            temp = temp.next
        new_count = count / 2

        while new_count == 0:
            temp2 = temp.next
            new_count -= 1
            print(temp2.val)

결국 실패했음

이것은 싱글 링크드리스트에 대한 개념과 두개의 포인터에 대한 개념을 알고 있어야 풀수 있는 문제이다.

맞춘 풀이

# 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: ListNode) -> ListNode:
        pre_node = post_node = head
        while pre_node and pre_node.next:
            pre_node = pre_node.next.next
            post_node = post_node.next
        return post_node

댓글