File tree 2 files changed +29
-19
lines changed
2 files changed +29
-19
lines changed Original file line number Diff line number Diff line change @@ -46,16 +46,22 @@ function CircularLinkedList() {
46
46
index = 0 ;
47
47
48
48
if ( position === 0 ) { //add on first position
49
-
50
- node . next = current ;
51
-
52
- //update last element
53
- while ( current . next !== head ) { //last element will be head instead of NULL
54
- current = current . next ;
49
+
50
+ if ( ! head ) { // if no node in list
51
+ head = node ;
52
+ node . next = head ;
53
+ } else {
54
+ node . next = current ;
55
+
56
+ //update last element
57
+ while ( current . next !== head ) { //last element will be head instead of NULL
58
+ current = current . next ;
59
+ }
60
+
61
+ head = node ;
62
+ current . next = head ;
55
63
}
56
-
57
- head = node ;
58
- current . next = head ;
64
+
59
65
60
66
} else {
61
67
while ( index ++ < position ) {
@@ -180,4 +186,5 @@ function CircularLinkedList() {
180
186
this . print = function ( ) {
181
187
console . log ( this . toString ( ) ) ;
182
188
} ;
183
- }
189
+ }
190
+
Original file line number Diff line number Diff line change @@ -58,15 +58,18 @@ let CircularLinkedList2 = (function () {
58
58
59
59
if ( position === 0 ) { //add on first position
60
60
61
- node . next = current ;
62
-
63
- //update last element
64
- while ( current . next !== this . getHead ( ) ) { //last element will be head instead of NULL
65
- current = current . next ;
66
- }
67
-
68
- head . set ( this , node ) ;
69
- current . next = this . getHead ( ) ;
61
+ if ( ! this . getHead ( ) ) { // if no node in list
62
+ head . set ( this , node ) ;
63
+ node . next = this . getHead ( ) ;
64
+ } else {
65
+ node . next = current ;
66
+ //update last element
67
+ while ( current . next !== this . getHead ( ) ) { //last element will be head instead of NULL
68
+ current = current . next ;
69
+ }
70
+ head . set ( this , node ) ;
71
+ current . next = this . getHead ( ) ;
72
+ }
70
73
71
74
} else {
72
75
while ( index ++ < position ) {
You can’t perform that action at this time.
0 commit comments