我們先從數(shù)組創(chuàng)建一個鏈表:
@interface ListNode : NSObject
@property (nonatomic, assign) NSInteger key;
@property (nonatomic, strong) ListNode *next;
@end
@interface List : NSObject
-(instancetype)initFromArr:(NSArray *)arr;
@end
@implementation ListNode
@end
@interface List()
@property (nonatomic, strong) ListNode *head;
@end
@implementation List
-(instancetype)initFromArr:(NSArray *)arr {
self = [super init];
if (self) {
ListNode *preNode;
for (NSNumber *value in arr) {
if (_head == nil) {
_head = [[ListNode alloc] init];
_head.key = [value integerValue];
preNode = _head;
} else {
ListNode *newNode = [[ListNode alloc] init];
newNode.key = [value integerValue];
preNode.next = newNode;
preNode = newNode;
}
}
}
return self;
}
-(NSString *)description {
NSMutableString *result = [NSMutableString string];
ListNode *currentNode = self.head;
while (currentNode != nil) {
[result appendString:[NSString stringWithFormat:@"%lu -> ", currentNode.key]];
currentNode = currentNode.next;
}
[result appendString:@"null"];
return [result copy];
}
@end
測試下:
List *list = [[List alloc] initFromArr:@[@(1), @(2), @(3), @(4), @(5)]];
NSLog(@"%@", list);
2019-09-03 17:38:26.028129+0800 Algorithm[1880:1129933] 1 -> 2 -> 3 -> 4 -> 5 -> null
鏈表反轉(zhuǎn)
例如,我們要反轉(zhuǎn)下面這個鏈表:

鏈表反轉(zhuǎn)
只要重復2的動作一直到cur移動到最后的null節(jié)點,反轉(zhuǎn)就完成了。
示例代碼:
-(void)reverse {
ListNode *pre = nil;
ListNode *cur = self.head;
ListNode *next;
while (cur != nil) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
self.head = pre;
}
測試:
List *list = [[List alloc] initFromArr:@[@(1), @(2), @(3), @(4), @(5)]];
[list reverse];
NSLog(@"%@", list);
2019-09-03 17:40:46.705029+0800 Algorithm[1883:1130326] 5 -> 4 -> 3 -> 2 -> 1 -> null