File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
0234-palindrome-linked-list Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments