File tree Expand file tree Collapse file tree 2 files changed +29
-19
lines changed
Expand file tree Collapse file tree 2 files changed +29
-19
lines changed Original file line number Diff line number Diff line change @@ -46,16 +46,22 @@ function CircularLinkedList() {
4646 index = 0 ;
4747
4848 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 ;
5563 }
56-
57- head = node ;
58- current . next = head ;
64+
5965
6066 } else {
6167 while ( index ++ < position ) {
@@ -180,4 +186,5 @@ function CircularLinkedList() {
180186 this . print = function ( ) {
181187 console . log ( this . toString ( ) ) ;
182188 } ;
183- }
189+ }
190+
Original file line number Diff line number Diff line change @@ -58,15 +58,18 @@ let CircularLinkedList2 = (function () {
5858
5959 if ( position === 0 ) { //add on first position
6060
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+ }
7073
7174 } else {
7275 while ( index ++ < position ) {
You can’t perform that action at this time.
0 commit comments