数据
#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
下一篇双链表的实现