Skip to content

Commit 93ed38b

Browse files
committed
Time: 2 ms (99.56%), Space: 78.7 MB (58.19%) - LeetHub
1 parent deaa08c commit 93ed38b

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number
5+
* next: ListNode | null
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
* }
11+
*/
12+
13+
// 연결 리스트 팰린드롬 공식 = 중간 찾고 + 뒤집고 + 마주보기
14+
function isPalindrome(head: ListNode | null): boolean {
15+
if (!head || !head.next) return true;
16+
17+
// 1. 중간 찾기
18+
let slow: ListNode | null = head;
19+
let fast: ListNode | null = head;
20+
21+
while (fast && fast.next) {
22+
slow = slow.next;
23+
fast = fast.next.next;
24+
}
25+
26+
// 2. 뒤 절반 뒤집기
27+
let prev: ListNode | null = null;
28+
let curr: ListNode | null = slow;
29+
30+
while (curr) {
31+
const next = curr.next;
32+
curr.next = prev;
33+
prev = curr;
34+
curr = next;
35+
}
36+
37+
// 3. 앞쪽과 비교
38+
let left: ListNode | null = head;
39+
let right: ListNode | null = prev;
40+
41+
while (right) {
42+
if (left.val !== right.val) return false;
43+
left = left.next;
44+
right = right.next;
45+
}
46+
47+
return true;
48+
}

0 commit comments

Comments
 (0)