File tree Expand file tree Collapse file tree 1 file changed +83
-0
lines changed
Expand file tree Collapse file tree 1 file changed +83
-0
lines changed Original file line number Diff line number Diff line change 1+ //Stack using linkedlist
2+ function stackUsingLL ( ) {
3+ //Node
4+ let Node = function ( elm ) {
5+ this . element = elm ;
6+ this . next = null ;
7+ }
8+
9+ //To keep track of the size
10+ let length = 0 ;
11+
12+ //To keep track of the list
13+ let head = null ;
14+
15+ //Push data in the stack
16+ this . push = function ( elm ) {
17+ //Create a new node
18+ let node = new Node ( elm ) ,
19+ current ;
20+
21+ //Add the new node at the top
22+ current = head ;
23+ node . next = current ;
24+ head = node ;
25+
26+ length ++ ;
27+ }
28+
29+ //Pop the item from the stack
30+ this . pop = function ( ) {
31+ let current = head ;
32+
33+ //If there is item then remove it
34+ //and make the next element as the first
35+ if ( current ) {
36+ let elm = current . element ;
37+ current = current . next ;
38+ head = current ;
39+ length -- ;
40+ return elm ;
41+ }
42+
43+ return null ;
44+ }
45+
46+ //Return the first element in the stack
47+ this . peek = function ( ) {
48+ if ( head ) {
49+ return head . element ;
50+ }
51+
52+ return null ;
53+ }
54+
55+ //Convert the stack to an array
56+ this . toArray = function ( ) {
57+ let arr = [ ] ;
58+ let current = head ;
59+ while ( current ) {
60+ arr . push ( current . element ) ;
61+ current = current . next ;
62+ }
63+
64+ return arr ;
65+ }
66+
67+ //Check if stack is empty
68+ this . isEmpty = function ( ) {
69+ return length === 0 ;
70+ }
71+
72+ //Return the size of the stack
73+ this . size = function ( ) {
74+ return length ;
75+ }
76+
77+ //Clear the stack
78+ this . clear = function ( ) {
79+ head = null ;
80+ length = 0 ;
81+ }
82+
83+ }
You can’t perform that action at this time.
0 commit comments