File tree Expand file tree Collapse file tree 2 files changed +85
-12
lines changed Expand file tree Collapse file tree 2 files changed +85
-12
lines changed Original file line number Diff line number Diff line change @@ -38,21 +38,38 @@ class LinkedList {
3838 n = n . next ;
3939 }
4040 }
41+
42+ // O(n)
43+ toString ( ) {
44+ let data = [ ] ;
45+ let n = this . head ;
46+ while ( n ) {
47+ data . push ( n . data ) ;
48+ n = n . next ;
49+ }
50+ return data . join ( ' -> ' ) ;
51+ }
4152}
4253
43- let list = new LinkedList ( ) ;
44- list . add ( 1 ) ;
45- list . add ( 2 ) ;
46- list . add ( 3 ) ;
47- list . add ( 4 ) ;
54+ function test ( ) {
55+ let list = new LinkedList ( ) ;
56+ list . add ( 1 ) ;
57+ list . add ( 2 ) ;
58+ list . add ( 3 ) ;
59+ list . add ( 4 ) ;
60+
61+ console . log ( list ) ;
62+
63+ list . delete ( 4 ) ;
64+ console . log ( list ) ;
4865
49- console . log ( list ) ;
66+ list . delete ( 2 ) ;
67+ console . log ( list ) ;
5068
51- list . delete ( 4 ) ;
52- console . log ( list ) ;
69+ list . delete ( 1 ) ;
70+ console . log ( list ) ;
71+ } ;
5372
54- list . delete ( 2 ) ;
55- console . log ( list ) ;
73+ // test();
5674
57- list . delete ( 1 ) ;
58- console . log ( list ) ;
75+ module . exports = LinkedList ;
Original file line number Diff line number Diff line change 1+ let LinkedList = require ( './linkedlist' ) ;
2+
3+ LinkedList . prototype . dedub = function ( ) {
4+ let map = new Map ( ) ;
5+ let n = this . head ;
6+ map . set ( n . data , 1 ) ;
7+
8+ while ( n && n . next ) {
9+ let data = n . next . data ;
10+ map . set ( data , 1 ) ;
11+
12+ if ( map . get ( data ) ) {
13+ n . next = n . next . next ;
14+ }
15+
16+ n = n . next ;
17+ }
18+ } ;
19+
20+ LinkedList . prototype . dedub2 = function ( ) {
21+ for ( let c = this . head ; c ; c = c . next ) {
22+ for ( let n = c ; n && n . next ; n = n . next ) {
23+ let data = n . next . data ;
24+
25+ if ( c . data === data ) {
26+ n . next = n . next . next ;
27+ }
28+ }
29+ }
30+ } ;
31+
32+ function test ( ) {
33+ let list = new LinkedList ( ) ;
34+ list . add ( 1 ) ;
35+ list . add ( 1 ) ;
36+ list . add ( 2 ) ;
37+ list . add ( 2 ) ;
38+ console . log ( list . toString ( ) ) ;
39+
40+ list . dedub ( ) ;
41+
42+ console . log ( list . toString ( ) ) ;
43+
44+ list = new LinkedList ( ) ;
45+ list . add ( 1 ) ;
46+ list . add ( 1 ) ;
47+ list . add ( 2 ) ;
48+ list . add ( 2 ) ;
49+ console . log ( list . toString ( ) ) ;
50+
51+ list . dedub2 ( ) ;
52+
53+ console . log ( list . toString ( ) ) ;
54+ }
55+
56+ test ( ) ;
You can’t perform that action at this time.
0 commit comments