[Medium] 143. Reorder List

문제

https://leetcode.com/problems/reorder-list/

 

Reorder List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

You are given the head of a singly linked-list. The list can be represented as:

L0 → L1 → … → Ln - 1 → Ln

Reorder the list to be on the following form:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

You may not modify the values in the list's nodes. Only nodes themselves may be changed.

 

단일 연결 목록의 선두가 부여됩니다. 목록은 다음과 같이 나타낼 수 있다.

L0 → L1 → … → Ln - 1 → Ln

다음 양식에 맞게 목록 순서를 변경합니다.

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

목록의 노드에서 값을 수정할 수 없습니다. 노드 자체만 변경할 수 있습니다.

 

예시

Example 1:

Input: head = [1,2,3,4]
Output: [1,4,2,3]

Example 2:

Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]

 

제약 조건

Constraints:

  • The number of nodes in the list is in the range [1, 5 * 104].
  • 1 <= Node.val <= 1000

 

해결 코드

/**
 * 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 {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function(head) {
     if (!head || !head.next) return; 
    
    // 중간 point 찾기
    let slow = head, fast = head;
    while(fast.next && fast.next.next) {
        slow = slow.next;
        fast = fast.next.next;
    }
    
    // head와 part2로 나누기
    let part2 = slow.next;
    slow.next = null;
    
    // reverse part 2
    let prev = null, cur = part2, next = cur.next;
    while(cur) {
        next = cur.next;
        cur.next = prev;
        prev = cur;
        cur = next;
    }
    
    part2 = prev;
    
    // head와 part2 합치기
    while(head && part2) {
        let p1 = head.next;
        let p2 = part2.next
        head.next = part2;
        head.next.next = p1;
        part2 = p2;
        head = p1;
    }
    
    return head;
};