Code:Linked list in Objective-C, with head and tail pointers

Few days ago, I explained how to construct a dynamic data structure like a linked list the operations that can be done on a linked list.

A singly linked list can have two pointers, one at the head of the list and one at the tail. Tail pointer is really useful, when a node has to inserted at the tail with the head pointer only, its a long traversal if the data set is large. Here in this implementation, I have used head and tail pointers to easily add and delete nodes.

Both head and tail pointers are aware of each other, meaning, if a node if inserted at the tail in an empty list, and then printed from the head, the single node is printed starting from the head and vice versa.

Head and tail pointers are made aware of each other during all insert and delete operations.

One caveat is, when deleting a node at the tail, there is no way in a singly linked list just to use the tail pointer and not to loose the tail position, so the list has to be traversed from the head to delete the node at the tail and preserve tail position.

Callback blocks:

Client which uses this data structure, has an option to get notified in the event of a successful or failed operation How? callback blocks can be passed along with the operation, Refer test cases in the code.

Operations implemented are:

Print:
  1. Print from the head
  2. Print from the tail
  3. Print in reverse
Insert:
  1. Insert node at head
  2. Insert node at tail
  3. Insert node after a target data
Delete:
  1. Delete node at head
  2. Delete node at tail
  3. Delete node with target data

A complete implementation of this data structure is implemented in Objective-C and available at GitHub(https://github.com/jkeynes81/LinkedList.git)

Fork it,Star it,Clone it and if you feel anything can be improved, send me a pull request.

 

Leave a Reply

Your email address will not be published. Required fields are marked *