ZBLOG

oc 头文件类的形式实现链表

下面是一个使用 Objective-C 头文件类的形式实现链表的示例代码:

LinkedListNode.h(头文件):

#import <Foundation/Foundation.h>

@interface LinkedListNode : NSObject

@property (nonatomic, strong) id data;
@property (nonatomic, strong) LinkedListNode *next;

- (instancetype)initWithData:(id)data;

@end

LinkedList.h(头文件):

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

@interface LinkedList : NSObject

@property (nonatomic, strong) LinkedListNode *head;

- (void)insertAtEnd:(id)data; // 在链表末尾插入节点
- (void)removeAtEnd; // 移除链表末尾的节点
- (void)printList; // 打印链表元素

@end

LinkedList.m(实现文件):

#import "LinkedList.h"

@implementation LinkedList

- (void)insertAtEnd:(id)data {
    if (!self.head) {
        self.head = [[LinkedListNode alloc] initWithData:data];
    } else {
        LinkedListNode *current = self.head;
        while (current.next != nil) {
            current = current.next;
        }
        current.next = [[LinkedListNode alloc] initWithData:data];
    }
}

- (void)removeAtEnd {
    if (!self.head || !self.head.next) {
        self.head = nil;
        return;
    }

    LinkedListNode *previous = nil;
    LinkedListNode *current = self.head;
    
    while (current.next != nil) {
        previous = current;
        current = current.next;
    }
    
    previous.next = nil;
}

- (void)printList {
    if (!self.head) {
        NSLog(@"Linked list is empty.");
        return;
    }

    LinkedListNode *current = self.head;
    
    while (current != nil) {
        NSLog(@"%@", current.data);
        current = current.next;
    }
}

@end

在上述代码中,我们创建了一个名为 LinkedListNode 的节点类和一个名为 LinkedList 的链表类。每个节点对象具有数据 (data) 和指向下一个节点的指针 (next)。链表类维护一个头结点 (head) 指针,用于表示链表的起始位置。

链表类包含插入末尾、移除末尾和打印链表元素等方法,通过操作节点对象来实现这些功能。

你可以将以上代码保存为三个文件,然后在需要使用链表的地方引入 LinkedList.h 头文件即可使用该链表类。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=10548

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?