File tree Expand file tree Collapse file tree 1 file changed +116
-0
lines changed Expand file tree Collapse file tree 1 file changed +116
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node {
2
+ constructor ( value ) {
3
+ this . value = value ;
4
+ this . next = null ;
5
+ }
6
+ }
7
+
8
+ class LinkedList {
9
+ constructor ( ) {
10
+ this . head = null ;
11
+ this . tail = null ;
12
+ this . size = 0 ;
13
+ }
14
+
15
+ isEmpty ( ) {
16
+ return this . size === 0 ;
17
+ }
18
+
19
+ getSize ( ) {
20
+ return this . size ;
21
+ }
22
+
23
+ prepend ( value ) {
24
+ const node = new Node ( value ) ;
25
+ if ( this . isEmpty ( ) ) {
26
+ this . head = node ;
27
+ this . tail = node ;
28
+ } else {
29
+ node . next = this . head ;
30
+ this . head = node ;
31
+ }
32
+ this . size ++ ;
33
+ }
34
+
35
+ append ( value ) {
36
+ const node = new Node ( value ) ;
37
+ if ( this . isEmpty ( ) ) {
38
+ this . head = node ;
39
+ this . tail = node ;
40
+ } else {
41
+ this . tail . next = node ;
42
+ this . tail = node ;
43
+ }
44
+ this . size ++ ;
45
+ }
46
+
47
+ removeFromFront ( ) {
48
+ if ( this . isEmpty ( ) ) {
49
+ return null ;
50
+ }
51
+ const value = this . head . value ;
52
+ this . head = this . head . next ;
53
+ this . size -- ;
54
+ return value ;
55
+ }
56
+
57
+ removeFromEnd ( ) {
58
+ if ( this . isEmpty ( ) ) {
59
+ return null ;
60
+ }
61
+ const value = this . tail . value ;
62
+ if ( this . size === 1 ) {
63
+ this . head = null ;
64
+ this . tail = null ;
65
+ } else {
66
+ let prev = this . head ;
67
+ while ( prev . next !== this . tail ) {
68
+ prev = prev . next ;
69
+ }
70
+ prev . next = null ;
71
+ this . tail = prev ;
72
+ }
73
+ this . size -- ;
74
+ return value ;
75
+ }
76
+
77
+ reverse ( ) {
78
+ let current = this . head ;
79
+ let prev = null ;
80
+ let next = null ;
81
+ while ( current ) {
82
+ next = current . next ;
83
+ current . next = prev ;
84
+ prev = current ;
85
+ current = next ;
86
+ }
87
+ this . tail = this . head ;
88
+ this . head = prev ;
89
+ }
90
+
91
+ print ( ) {
92
+ if ( this . isEmpty ( ) ) {
93
+ console . log ( "List is empty" ) ;
94
+ } else {
95
+ let curr = this . head ;
96
+ let list = "" ;
97
+ while ( curr ) {
98
+ list += `${ curr . value } ->` ;
99
+ curr = curr . next ;
100
+ }
101
+ console . log ( list ) ;
102
+ }
103
+ }
104
+ }
105
+
106
+ const list = new LinkedList ( ) ;
107
+ list . append ( 1 ) ;
108
+ list . append ( 2 ) ;
109
+ list . append ( 3 ) ;
110
+ list . prepend ( 0 ) ;
111
+ list . print ( ) ;
112
+ console . log ( list . getSize ( ) ) ;
113
+ list . removeFromFront ( ) ;
114
+ list . print ( ) ;
115
+ list . removeFromEnd ( ) ;
116
+ list . print ( ) ;
You can’t perform that action at this time.
0 commit comments