iOS 数据结构之链表

点击上方“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) {

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值