File tree Expand file tree Collapse file tree 1 file changed +97
-0
lines changed
Data-Structures/Linked-List Expand file tree Collapse file tree 1 file changed +97
-0
lines changed Original file line number Diff line number Diff line change 1+ class Node {
2+ constructor ( data , next = null ) {
3+ this . data = data
4+ this . next = next
5+ }
6+ }
7+
8+ class SinglyCircularLinkedList {
9+ constructor ( ) {
10+ this . head = null
11+ this . size = 0
12+ }
13+
14+ insert ( data ) {
15+ const node = new Node ( data )
16+
17+ if ( ! this . head ) {
18+ node . next = node
19+ this . head = node
20+ this . size ++
21+ } else {
22+ node . next = this . head
23+
24+ let current = this . head
25+
26+ while ( current . next . data !== this . head . data ) {
27+ current = current . next
28+ }
29+
30+ current . next = node
31+ this . size ++
32+ }
33+ }
34+
35+ insertAt ( index , data ) {
36+ const node = new Node ( data )
37+
38+ if ( index < 0 || index > this . size ) return
39+
40+ if ( index === 0 ) {
41+ this . head = node
42+ this . size = 1
43+ return
44+ }
45+
46+ let previous
47+ let count = 0
48+ let current = this . head
49+
50+ while ( count < index ) {
51+ previous = current
52+ current = current . next
53+ count ++
54+ }
55+
56+ node . next = current
57+ previous . next = node
58+ this . size ++
59+ }
60+
61+ remove ( ) {
62+ if ( ! this . head ) return
63+
64+ let prev
65+ let current = this . head
66+
67+ while ( current . next !== this . head ) {
68+ prev = current
69+ current = current . next
70+ }
71+
72+ prev . next = this . head
73+ this . size --
74+ }
75+
76+ printData ( ) {
77+ let count = 0
78+ let current = this . head
79+
80+ while ( current !== null && count !== this . size ) {
81+ console . log ( current . data + '\n' )
82+ current = current . next
83+ count ++
84+ }
85+ }
86+ }
87+
88+ const ll = new SinglyCircularLinkedList ( )
89+
90+ ll . insert ( 10 )
91+ ll . insert ( 20 )
92+ ll . insert ( 30 )
93+ ll . insert ( 40 )
94+ ll . insert ( 50 )
95+ ll . insertAt ( 5 , 60 )
96+ ll . remove ( 5 )
97+ ll . printData ( )
You can’t perform that action at this time.
0 commit comments