PS/LeetCode

LeetCode / Linked List / 328번 / Odd Even Linked List / JS

KimMinJun 2023. 4. 28. 17:16

< 문제 바로가기 >

 

Odd Even Linked List - LeetCode

Can you solve this real interview question? Odd Even Linked List - Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered od

leetcode.com

 

< 문제 간단설명 >

홀수번째 노드들을 앞으로 오게 하고, 짝수번째 노드들은 뒤로 보낸다.

 

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var oddEvenList = function(head) {
    if(!head) return head;

    // head의 맨 처음을 가리키도록
    let oddList = head;
    // head의 맨 처음노드의 다음을 가리키도록(2번째)
    let evenList = head.next;

    let oddListHead = oddList;
    let evenListHead = evenList;

    // 한칸씩 건너뛰면서 홀수와 짝수번째 각각 알맞게 next로 설정
    while(oddList.next && evenList.next) {
        oddList.next = oddList.next.next;
        oddList = oddList.next;

        evenList.next = evenList.next.next;
        evenList = evenList.next;
    }

    // 홀수번째 리스트 다음에 짝수번째 리스트가 오도록
    oddList.next = evenListHead;
    let result = oddListHead;

    return result;
};