.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]

 

๊ฐ์ƒํ‰

  • ๋ง์Šค๋“œ ๋ฆฌ์ŠคํŠธ๋Š” ์ฐธ ์–ด๋ ต๋‹ค. ์ฃผ์†Œ ์ฐธ์กฐ์— ๋Œ€ํ•ด์„œ๋„ ์•Œ๊ณ  ์ฃผ์‹œํ•˜๊ณ  ์žˆ์–ด์•ผํ•œ๋‹ค. ๊ท€์ฐฎ.

'coding test > leetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[leetCode/JS] 872. Leaf-Similar Trees  (0) 2022.12.08
[leetCode/JS] 938. Range Sum of BST  (0) 2022.12.07
[leetCode/JS] 876. Middle of the Linked List  (0) 2022.12.05
[leetCode/JS] 2256. Minimum Average Difference  (0) 2022.12.04
[leetCode/JS] 451. Sort Characters By Frequency  (0) 2022.12.03
0 Comments
๋Œ“๊ธ€์“ฐ๊ธฐ ํผ