Possible Duplicate:
Creating Linked Lists in Objective C
I am trying to understand what a linked list is. Is there anyway of implementing it in Objective-C or some sample code?
Possible Duplicate:
Creating Linked Lists in Objective C
I am trying to understand what a linked list is. Is there anyway of implementing it in Objective-C or some sample code?
Linked list are useful in C to handle dynamic-length lists. This is not an issue in objective-C as you have NSMutableArray.
So the equivalent of:
struct my_list {
int value;
struct my_list *next;
};
struct my_list list1;
struct my_list list2;
list1.next = &list2;
list1.value = 5;
list2.value = 10;
Would be:
NSMutableArray* array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithInt:5]];
[array addObject:[NSNumber numberWithInt:10]];
Of course, you can use classic linked-list in an objective-c application.
NSMutableArrays have a certain capacity which is the number of elements that it can contain without reallocating. Appending to linked lists performs in O(1), while appending to the end of arrays takes amortized O(1), which is different. So no, using NSMutableArray is not the same thing in all accounts. However, if performance is not an issue, go ahead. If it is, you should consider what you'll be doing most often, because indexing in linked lists is slow (O(n)), for instance.list1.next = &list2;?list2 struct to the next field of list1.