4

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?

4

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It is an issue for certain use cases. It's much faster to add items to the beginning of a linked list, as the rest of the list does not have to be touched. In an array they'd have to be shifted backwards. Also, in certain (immutable) data structures you can share common branches easily. Of course, if all you do is add items to the end, then an NSMutableArray would be better.
Even when adding to the end linked lists are superior to arrays. 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.
What does this line do: list1.next = &list2;?
@ArielSD assigns the address of list2 struct to the next field of list1.
2

there is no need to use of array. MyEvent object also conitan next MyEvent. so you just create next of next object. so just you need to init.

e.g.

MyEvent *obj = [[MyEvent alloc]init];

child node.

obj.nextEvent = [[MyEvent alloc]init];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.