.Zzumbong

[leetCode/JS] 328. Odd Even Linked List 본문

coding test/leetCode

[leetCode/JS] 328. Odd Even Linked List

쭘봉 2022. 12. 6. 10:21

난이도 [ 🤔 ] Medium 

 

문제 설명 

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 odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

짝수는 링크드 링크드리스트는 뒤로 보낸다.

 

 

 

입출력 예

Example 1:

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

 

 

Example 2:

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

 

Constraints

  • The number of nodes in the linked list is in the range [0, 104].
  • -106 <= Node.val <= 106

 

 

 


내 솔루션

  • 자세한 사항은 console.log()를 보며 차근차근 따라해보자.
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
function oddEvenList(head) {
  if (!head) return head;
  
  var odd = head;
  var even = head.next;
  while (odd.next && odd.next.next) {
    var tmp = odd.next;
	
    // 1
    odd.next = odd.next.next;

	// 2
    odd = odd.next;

	// 3
    tmp.next = odd.next;
    
    // 4
  }
  odd.next = even;
  console.log(head)
  return head;
}

// { head: [1,2,3,4,5], odd: [1,2,3,4,5], even: [2,3,4,5] }
// 1  { odd: [1,2,3,4,5], even: [2,3,4,5], tmp: [2,3,4,5] }
// 2  { odd: [1,3,4,5], even: [2,3,4,5], tmp: [2,3,4,5] }
// 3  { odd: [3,4,5], even: [2,3,4,5], tmp: [2,3,4,5] }
// 4  { odd: [3,4,5], even: [2,4,5], tmp: [2,4,5] }
// 1  { odd: [3,4,5], even: [2,4,5], tmp: [4,5] }
// 2  { odd: [3,5], even: [2,4,5], tmp: [4,5] }
// 3  { odd: [5], even: [2,4,5], tmp: [4,5] }
// 4  { odd: [5], even: [2,4], tmp: [4] }
// [1,3,5,2,4]

 

감상평

  • 링스드 리스트는 참 어렵다. 주소 참조에 대해서도 알고 주시하고 있어야한다. 귀찮.
Comments