[LeetCode] 2095. Delete the Middle Node of a Linked List, Medium

2025. 4. 17. 14:01·CodingTest/LeetCode
반응형

1. 문제

  • 연결 리스트가 주어질 때, 중간 노드를 제외한 리스트를 반환하라.
  • 중간 노드는 전체 길이 n/2 위치한다.

2. 해결

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function deleteMiddle(head: ListNode | null): ListNode | null {
    let n = 1;

    let current = head;
    while(current.next) {
        n++;
        current = current.next;
    }

    if(n === 1) return null;

    let idx = 0;
    current = head;

    while(current.next && idx < Math.floor(n / 2)- 1) {
        current = current.next;
        idx++;
    }

    if(current.next) current.next = current.next.next
    return head;
};
  • 전체 노드를 순회하면서 길이를 구하고, 다시 한 번 순회해서 중간 노드의 이전 노드를 찾는다.
  • 찾은 노드의 next를 갱신.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 872. Leaf-Similar Trees, Easy
  • [LeetCode] 2130. Maximum Twin Sum of a Linked List, Medium
  • [LeetCode] 649. Dota2 Senate, Medium
  • [LeetCode] 933. Number of Recent Calls, Easy
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Java
    Easy
    meidum
    next 14
    백준1260
    알고리즘
    boj2108
    medium
    백준2751
    프로그래머스
    백준1427
    component-scan
    TypeScript
    백준7576자바
    백준7576
    leetcode 2236
    BOJ
    boj1427
    백준
    자바
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 2095. Delete the Middle Node of a Linked List, Medium
상단으로

티스토리툴바