File tree Expand file tree Collapse file tree 1 file changed +16
-11
lines changed Expand file tree Collapse file tree 1 file changed +16
-11
lines changed Original file line number Diff line number Diff line change 11const LinkedList = require ( './linkedlist' ) ;
22
3+ /**
4+ * Found is a linkedList elements are a palindrome.
5+ * assumes that we don't know the size of the list, thus using the two pointers (fast/slow runner).
6+ * @returns {boolean }
7+ */
38LinkedList . prototype . isPalindrome = function ( ) {
49 const stack = [ ] ;
5- let i1 = this . head ;
6- let i2 = this . head ;
10+ let slow = this . head ;
11+ let fast = this . head ;
712
8- if ( this . size ( ) === 1 ) {
13+ if ( fast . next === null ) {
914 return true ;
1015 }
1116
12- stack . push ( i1 . data ) ;
17+ stack . push ( slow . data ) ;
1318
1419 // collect element up to the middle
15- while ( i2 . next && i2 . next . next ) {
16- i1 = i1 . next ;
17- i2 = i2 . next . next ;
18- if ( i2 . next ) { stack . push ( i1 . data ) ; }
20+ while ( fast . next && fast . next . next ) {
21+ slow = slow . next ;
22+ fast = fast . next . next ;
23+ if ( fast . next ) { stack . push ( slow . data ) ; }
1924 }
2025
2126 // compare they are the same as the second half
22- while ( i1 . next ) {
23- i1 = i1 . next ;
24- if ( stack . pop ( ) !== i1 . data ) {
27+ while ( slow . next ) {
28+ slow = slow . next ;
29+ if ( stack . pop ( ) !== slow . data ) {
2530 return false ;
2631 }
2732 }
You can’t perform that action at this time.
0 commit comments