ZBLOG

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

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

LinkedListNode.h(头文件):

  1. #import <Foundation/Foundation.h>
  2. @interface LinkedListNode : NSObject
  3. @property (nonatomic, strong) id data;
  4. @property (nonatomic, strong) LinkedListNode *next;
  5. - (instancetype)initWithData:(id)data;
  6. @end

LinkedList.h(头文件):

  1. #import <Foundation/Foundation.h>
  2. #import "LinkedListNode.h"
  3. @interface LinkedList : NSObject
  4. @property (nonatomic, strong) LinkedListNode *head;
  5. - (void)insertAtEnd:(id)data; // 在链表末尾插入节点
  6. - (void)removeAtEnd; // 移除链表末尾的节点
  7. - (void)printList; // 打印链表元素
  8. @end

LinkedList.m(实现文件):

  1. #import "LinkedList.h"
  2. @implementation LinkedList
  3. - (void)insertAtEnd:(id)data {
  4. if (!self.head) {
  5. self.head = [[LinkedListNode alloc] initWithData:data];
  6. } else {
  7. LinkedListNode *current = self.head;
  8. while (current.next != nil) {
  9. current = current.next;
  10. }
  11. current.next = [[LinkedListNode alloc] initWithData:data];
  12. }
  13. }
  14. - (void)removeAtEnd {
  15. if (!self.head || !self.head.next) {
  16. self.head = nil;
  17. return;
  18. }
  19. LinkedListNode *previous = nil;
  20. LinkedListNode *current = self.head;
  21. while (current.next != nil) {
  22. previous = current;
  23. current = current.next;
  24. }
  25. previous.next = nil;
  26. }
  27. - (void)printList {
  28. if (!self.head) {
  29. NSLog(@"Linked list is empty.");
  30. return;
  31. }
  32. LinkedListNode *current = self.head;
  33. while (current != nil) {
  34. NSLog(@"%@", current.data);
  35. current = current.next;
  36. }
  37. }
  38. @end

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

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

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?