Skip to content

Instantly share code, notes, and snippets.

@troyharris
Last active December 22, 2015 06:28
Show Gist options
  • Save troyharris/6430742 to your computer and use it in GitHub Desktop.
Save troyharris/6430742 to your computer and use it in GitHub Desktop.
A simple linked list object in Objective-C
@interface TRHLinkedNode : NSObject
@property (nonatomic, strong) NSString *dogName;
@property (nonatomic, string) TRHLinkedNode *nextNode;
- (void)appendItemToEnd(TRHLinkedNode *)item;
+ (void)searchAndDeleteFromLinkedList:(NSString *)dog afterItem:(TRHLinkedNode)headNode;
@end
@implementation TRHLinkedNode
- (void)appendItemToEnd(TRHLinkedList *)item {
TRHLinkedNode *n = self;
while (n.nextNode) {
n = n.nextNode;
}
n.nextNode = item;
}
+ (void)searchAndDeleteFromLinkedList:(NSString *)dog afterItem:(TRHLinkedNode)headNode {
TRHLinkedNode *parentNode;
TRHLinkedNode *currentNode = headNode;
BOOL stop = NO;
while (!stop) {
if ([currentNode.dogName isEqualToString:dog]) {
parentNode.nextNode = currentNode.nextNode;
currentNode.nextNode = nil;
stop = YES;
} else {
if (!currentNode.nextNode) {
stop = YES;
}
}
}
}
/*
* Implement like so:
* TRHLinkedNode *item1 = [[TRHLinkedNode alloc] init];
* TRHLinkedNode *item2 = [[TRHLinkedNode alloc] init];
* item1.name = @"Watson";
* item2.name = @"Luna";
* item1.nextNode = item2;
* TRHLinkedNode *item3 = [[TRHLinkedNode alloc] init];
* item3.name = @"Cheese";
* [item1 appendItemToEnd:item3];
* [TRHLinkedNode searchAndDeleteFromLinkedList:@"Luna" afterItem:item1];
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment