点击上方“iOS开发”,选择“置顶公众号”
关键时刻,第一时间送达!
链表(Linked List)是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的,表现形式如下图所示:
单链表
双链表
数组和链表区别:
-
数组:数组元素在内存上连续存放,可以通过下标查找元素;插入、删除需要移动大量元素,比较适用于元素很少变化的情况
-
链表:链表中的元素在内存中不是顺序存储的,查找慢,插入、删除只需要对元素指针重新赋值,效率高
Objective-C 里没有现成的链表结构,下面我实现了非线程安全的单链表和双链表,以下都是具体的实现细节,完整代码可以在这儿下载
单链表
单链表提供了插入、删除、查询、反转等操作,具体实现如下:
BBSingleLinkedList.h
#import <Foundation/Foundation.h>
@interface BBSingleLinkedNode : NSObject <NSCopying>
@property (nonatomic, strong) NSString *key;
@property (nonatomic, strong) NSString *value;
@property (nonatomic, strong) BBSingleLinkedNode *next;
- (instancetype)initWithKey:(NSString *)key
value:(NSString *)value;
+ (instancetype)nodeWithKey:(NSString *)key
value:(NSString *)value;
@end
@interface BBSingleLinkedList : NSObject
- (void)insertNode:(BBSingleLinkedNode *)node;
- (void)insertNodeAtHead:(BBSingleLinkedNode *)node;
- (void)insertNode:(BBSingleLinkedNode *)newNode beforeNodeForKey:(NSString *)key;
- (void)insertNode:(BBSingleLinkedNode *)newNode afterNodeForKey:(NSString *)key;
- (void)bringNodeToHead:(BBSingleLinkedNode *)node;
- (void)removeNode:(BBSingleLinkedNode *)node;
- (BBSingleLinkedNode *)nodeForKey:(NSString *)key;
- (BBSingleLinkedNode *)headNode;
- (BBSingleLinkedNode *)lastNode;
- (NSInteger)length;
- (BOOL)isEmpty;
- (void)reverse;
- (void)readAllNode;
@end
BBSingleLinkedList.m
#import "BBSingleLinkedList.h"
@implementation BBSingleLinkedNode
- (instancetype)initWithKey:(NSString *)key
value:(NSString *)value
{
if (self = [super init]) {
_key = key;
_value = value;
}
return self;
}
+ (instancetype)nodeWithKey:(NSString *)key
value:(NSString *)value
{
return [[[self class] alloc] initWithKey:key value:value];
}
#pragma mark - NSCopying
- (id)copyWithZone:(nullable NSZone *)zone
{
BBSingleLinkedNode *newNode = [[BBSingleLinkedNode allocWithZone:zone] init];
newNode.key = self.key;
newNode.value = self.value;
newNode.next = self.next;
return newNode;
}
@end
@interface BBSingleLinkedList ()
@property (nonatomic, strong) BBSingleLinkedNode *headNode;
@property (nonatomic, strong) NSMutableDictionary *innerMap;
@end
@implementation BBSingleLinkedList
- (instancetype)init
{
self = [super init];
if (self) {
_innerMap = [NSMutableDictionary new];
}
return self;
}
#pragma mark - public
- (void)insertNodeAtHead:(BBSingleLinkedNode *)node
{
if (!node || node.key.length == 0) {