Skip to content

Instantly share code, notes, and snippets.

@isoiphone
Created March 7, 2014 20:45
Show Gist options
  • Save isoiphone/9419702 to your computer and use it in GitHub Desktop.
Save isoiphone/9419702 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
#import <stdio.h>
@class Node;
@interface Node : NSObject
@property (strong) Node* next;
@property (assign) NSString* val;
@end
@implementation Node
+ (id)nodeWithVal:(NSString*)val
{
Node* tmp = [[Node alloc] init];
tmp.val = val;
return tmp;
}
@end
Node* reverse1(Node* list)
{
Node* prev = nil;
while (list) {
Node* next = list.next;
list.next = prev;
prev = list;
list = next;
}
return prev;
}
Node* reverse2(Node* list)
{
Node* r = nil;
while (list) {
Node* cur = list;
list = list.next;
cur.next = r;
r = cur;
}
return r;
}
void dump(Node* list)
{
for (Node* cur=list; cur!=nil; ) {
printf("%s", [cur.val UTF8String]);
cur=cur.next;
if (cur) {
printf(" -> ");
}
}
printf("\n");
}
int main (int argc, const char * argv[])
{
@autoreleasepool {
Node* list = [Node nodeWithVal:@"a"];
list.next = [Node nodeWithVal:@"b"];
list.next.next = [Node nodeWithVal:@"c"];
list.next.next.next = [Node nodeWithVal:@"d"];
dump(list);
list = reverse1(list);
dump(list);
list = reverse2(list);
dump(list);
}
}
// OUTPUT:
// running 72 lines of Objective-C
// a -> b -> c -> d
// d -> c -> b -> a
// a -> b -> c -> d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment