Notice
Recent Posts
Recent Comments
Link
์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- ์ ์ค
- ์ฝ๋ฉํ ์คํธ
- ์ ํฌ๋ธ
- ํ์ค์คํค
- ์ฝํ
- ์กํ
- javascript
- LeetCode
- ์ ์ค์๋ด
- ์ก๋ฆฌ๋จ
- ์ฐ์ฃผ
- ์๊ณ ๋ฆฌ์ฆ
- ๋์ซ
- ๊ฒ์
- Sort
- ์ ์ฅ
- ๋ง์ง
Archives
- Today
- Total
.Zzumbong
[leetCode/JS] 876. Middle of the Linked List ๋ณธ๋ฌธ
๋์ด๋ [ ๐ ] Easy
๋ฌธ์ ์ค๋ช
Given the head
of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
๋จ์ผ linked List ๋ฅผ ์ค๋ค. list์ ์ค๊ฐ ๋ถํฐ returnํ๋๋ฐ, ์ค๊ฐ์ด 2๊ฐ ์ธ ๊ฒฝ์ฐ(์ง์ length) ์ผ๋, 2๋ฒ์งธ ์ค๊ฐ ๊ฐ ๋ถํฐ return ํด์ค๋ค.
์ ์ถ๋ ฅ ์
Example 1:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
Constraints
- The number of nodes in the list is in the range
[1, 100]
. 1 <= Node.val <= 100
๋ด ์๋ฃจ์
- ์ฌ๋ฌ ๋ฐฉ์์ผ๋ก ํ๋ ์ค list ์์ฒด๋ฅผ arr์ ๋ฃ์ด์ ์ค๊ฐ ๊ฐ์ด ๋ค์ด์๋ ์์๋ง return ํ๊ธฐ๋กํจ.
/**
* 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}
*/
// head = [1,2,3,4,5,6];
var middleNode = function(head) {
const arr = [];
let length = 0;
let list = head;
while(list) {
length++;
arr.push(list)
list = list.next;
}
// arr = [ [1,2,3,4,5,6], [2,3,4,5,6], [3,4,5,6], [4,5,6], [5,6], [6] ]
return arr[Math.floor(length/2)] // [4,5,6]
};
const node = (list, fuc) => {
if(!list) return;
fuc(list);
node(list.next, fuc);
}
node(head, (list) => {
length++;
arr.push(list)
});
์ฒ์์ ์ํ๋ฅผ 2๋ฒํด์ ์ฌ๊ท์ function์ param์ผ๋ก ๋ณด๋ด์ ์ํ๋ฅผ ํ์๋ค.
์ต๊ณ ์ ์๋ฃจ์
- ์์ฐ.. ๊ฐ๋๋์ด
- fast.next.next๋ก 2์นธ์ฉ ๊ฑด๋๋ฐ์ด์ ๋ฉ์ท์ ๋, slow๊ฐ ์ค๊ฐ node๊ฐ ๋๋ค.
var middleNode = function(head) {
let slow = head;
let fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
};
๊ฐ์ํ
- linked list ๋ฌธ์ ๋ค์ ์ด๋ป๊ฒ ์ํํ ์ง ๊ณ ๋ฏผ์ด ๋์ด ํธ๋ ์๋๊ฐ ๋๋ ค์ง๊ณคํ๋ค.
- list && list.next๋ก while ๋๋ฆฌ๋๊ฒ ๊ฐ์ฅ ์ํธํ ๋ฏ.
- ์๊ฐ๋ณด๋ค ๋นจ๋๋ค.
'coding test > leetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[leetCode/JS] 938. Range Sum of BST (0) | 2022.12.07 |
---|---|
[leetCode/JS] 328. Odd Even Linked List (0) | 2022.12.06 |
[leetCode/JS] 2256. Minimum Average Difference (0) | 2022.12.04 |
[leetCode/JS] 451. Sort Characters By Frequency (0) | 2022.12.03 |
[leetCode/JS] 1657. Determine if Two Strings Are Close (0) | 2022.12.02 |
Comments