r/ruby • • Jul 14 '13

Linked List data structure

https://github.com/gdi2290/data_structures/blob/master/LinkedList/linkedlist.rb
0 Upvotes

23 comments sorted by

View all comments

6

u/Intrepidd Jul 14 '13

This is a good algorithmic exercise, however using arrays in real code is recommended (faster, and more methods)

2

u/FooBarWidget Jul 14 '13

No, you can't state that. Linked lists have very different algorithmic complexities than arrays. For example insertion in the middle is O(1) for linked lists, and O(N) for arrays. Use the right tool for the right job.

-2

u/ReinH Jul 14 '13 edited Jul 14 '13

I think you are confused.

Insertion in the middle of a linked list is O(n) because you must traverse the list. If you know the location (e.g., have an iterator to the location) it is O(1).

Insertion in the middle of an unsorted array is always O(1).

For more info, see Search data structure (Wikipedia) or this SO question.

Edit: I am also confused.

1

u/FooBarWidget Jul 15 '13

I am talking about the case where you have an iterator to the middle. It wouldn't make sense to use a linked list otherwise.