Middle of the Linked List

Nak.s·2023년 1월 4일
0

CodeTest

목록 보기
5/19

Singly Linked List 의 중간 Node를 찾아 해당 노드를 반환한다.

첫번째 방법
Singly Linked List의 총 길이 를 구한다음,
중간 Node 를 찾아 반환한다.

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode node = head;
        int count = 1;
        while(node.next != null){
            ++count;
            node = node.next;

        }
        count = count / 2 - 1;

        while(count > -1){
            --count;
            head = head.next;
        }
        return head;
    }
}

두번째 방법
Singly Linked List의 중간 Node를 구하므로,
while 문에서 a 변수에는 a Node의 다음값,
b변수에는 b Node의 다음다음 값을 할당하여,
b Node가 null 이 되는 지점의 a 값을 반환한다.

public ListNode middleNode(ListNode head) {
        ListNode a = head, b = head;
        while(a.next != null && a.next.next != null){
            a = a.next.next;
            b = b.next;
        }
        if(a.next != null)
            b = b.next;
        return b;
    }

두번째 방법이 첫번째 방법보다 속도상 이점이 있다.

profile
궁금함이 많은 개발자

0개의 댓글