0

Circular list | add at middle

Can we still optimize the code to add element at middle of circular list ? Appreciate your feedback on below code: https://code.sololearn.com/cs5WjnBmuUVd/?ref=app

1st Jun 2021, 3:44 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Réponses
+ 1
Maybe you could globally define a length for the list? Doing that will prevent the use of another loop to determine the bounds of the current list. You can keep track of the length by initializing a counter and incrementing/decrementimg it whenever you add/remove an item. Hopefully this helps
1st Jun 2021, 8:49 PM
Choe
Choe - avatar
+ 1
Yeah nice one... Probably making length of list as mylist class data member
1st Jun 2021, 9:33 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
You can also find the middle by using a classical 2 pointer approach. You can do that by traversing the list using two pointers. Move one pointer by one and the other pointers by two ( double the speed ). When the fast pointer reaches end, slower one would already be pointing at mid.
2nd Jun 2021, 1:20 AM
Arsenic
Arsenic - avatar
+ 1
Thanks Choe nd Arsenic
2nd Jun 2021, 11:38 AM
Ketan Lalcheta
Ketan Lalcheta - avatar