本文共 1757 字,大约阅读时间需要 5 分钟。
首先,我们需要创建一个名为Node的类,表示链表的节点。每个节点将包含数据和指向下一个节点的指针。
@interface Node : NSObject @property (nonatomic, strong) id next; @property (nonatomic, copy) id data;
创建LinkedList类
接下来,我们创建一个名为LinkedList的类,表示链表本身。这个类将维护一个头节点和尾节点的引用。
@interface LinkedList : NSObject @property (nonatomic, strong) Node *head; @property (nonatomic, strong) Node *tail;实现尾插法
尾插法是将新节点插入到链表的末尾。具体步骤如下:
- 创建一个新的Node对象,并初始化其数据和指针。
- 获取链表的尾节点。
- 将新节点的指针赋值给尾节点的指针。
- 更新链表的尾节点指针。
- (Node *)appendNode { Node *newNode = [[Node alloc] init]; newNode.data = [someData]; if (self.tail.next == nil) { self.tail = newNode; } return newNode; }完整源码示例
以下是完整的Objective-C代码示例,展示了链表及其尾插法的实现。
#import@interface Node : NSObject @property (nonatomic, strong) id next; @property (nonatomic, copy) id data; @end @interface LinkedList : NSObject @property (nonatomic, strong) Node *head; @property (nonatomic, strong) Node *tail; - (Node *)appendNode; @end @implementation LinkedList - (Node *)appendNode { Node *newNode = [[Node alloc] init]; newNode.data = [someData]; if (self.tail.next == nil) { self.tail = newNode; } return newNode; } @end
转载地址:http://vnsfk.baihongyu.com/