OC 单链表的实现

 

数据
#import <Foundation/Foundation.h>

@interface Person : NSObject
@property (assign, nonatomic) NSUInteger age;
@end

#import "Person.h"

@implementation Person

@end

 

#import <Foundation/Foundation.h>
#import "Person.h"

节点

@interface LNode : NSObject
@property (strong, nonatomic) Person *data;//数据

@property (strong, nonatomic) LNode *next;//指向下一个节点

@end

 

@interface LNode()

@end

@implementation LNode
- (id)initWithData:(Person *)data
{
    self = [super init];
    if (self) {
        self.data = data;
        self.next = nil;
    }
    return self;
}

@end

链表

#import <Foundation/Foundation.h>
#import "LNode.h"

@interface LList : NSObject
@property (strong, nonatomic) LNode *head;//链表的头

@property( strong, nonatomic) LNode *lastNode;//链表的当前的最后一个结点,因为链表采用的是尾插法,以前一直用的头插法这次换个写法
-(void)append:(Person *)data;//插入结点的方法

-(Person *)delete:(LNode *)head num:(int)num;//删除结点的方法
-(void)print;//打印链表的方法

+(id)nodeList;//初始化链表的工厂方法,这里可以不用这个,只不过用了会方便一些,牵扯到设计模式就不多说了
@end

#import "LList.h"

@implementation LList

- (instancetype)initWithData:(Person *)data
{
    self = [super init];
    if (self) {
        self.head = [[LNode alloc]init];
        self.head.data = data;
        self.head.next = nil;
        self.lastNode = self.head;
    }
    return self;
}

+(id)listWithData:(Person *)data
{
    LList *firstNode = [[LList alloc]initWithData:data];
    return firstNode;
}


-(void)append:(Person *)data
{
    LNode *node = [LNode alloc];
    //初始化一个空元素
    node.next = self.lastNode.next;
    //最后一个元素下一个指向当前插入元素
    self.lastNode.next = node;
    //赋值
    node.data = data;
    
    self.lastNode = node;
}

//链表中删除结点
//    第一个参数是头节点,第二个参数是要删除第几个节点

-(Person *)delete:(LNode *)head num:(int)num
{
    int i = 0;
    Person *data;
    LNode *node = head;
    LNode *pSwap;
    if ((num < 1) && (node.next ==nil))
    {
        NSLog(@"删除失败!\n");
        return nil;
    }
    //    找到要找的节点的前驱
    while (i<num-1) {
        i++;
        node = node.next;
    }
    
    pSwap = node.next;
    //返回删除的数据
    data = pSwap.data;
    //前驱指向它的下下一个
    node.next = node.next.next;
    
    return data;
}

+(id)nodeList
{
    LNode *firstNode = [[LNode alloc]init];
    
    return firstNode;
}

//打印整个链表

-(void)print
{
    LNode *head = self.head;//其实这里不需要写self.head,直接写SHNode *head2 = self也是可以的
    while (head!=nil) {
        printf("%lu",(unsigned long)head.data.age);
        head = head.next;
    }
}

@end

 

下一篇双链表的实现

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值