本文共 2611 字,大约阅读时间需要 8 分钟。
Objective-C实现DoublyLinkedList双链表算法
以下是Objective-C中实现DoublyLinkedList(双链表)的代码示例,涵盖了基本操作如插入、删除和遍历等功能。
代码结构如下:
#import <Foundation/Foundation.h>
@interface Node : NSObject@property (nonatomic, strong) id data;@end
@implementation Node// 节点数据存储属性// 双链表节点类,用于存储数据和指向前后节点的指针@end
双链表是一种数据结构,具有双向链接的特点,支持从头尾两端进行操作。以下是双链表的实现步骤:
节点类定义:定义一个节点类,包含数据存储属性和指向前后节点的指针。
双链表类定义:创建一个管理双链表的类,包含节点操作方法。
插入节点:实现在双链表中插入新节点的功能,支持头尾插入和任意位置插入。
删除节点:实现删除节点的功能,支持按节点对象删除或按位置删除。
遍历双链表:实现遍历双链表的方法,可以是按顺序遍历或倒序遍历。
以下是完整的代码示例:
#import <Foundation/Foundation.h>
@interface DoublyLinkedList : NSObject{Node *head;Node *tail;}
// 节点类@interface Node : NSObject{id data;Node *next;Node *previous;}@property (nonatomic, strong) id data;@property (nonatomic, strong) Node *next;@property (nonatomic, strong) Node *previous;@end
// 双链表类实现@implementation DoublyLinkedList
// 初始化双链表
// 插入节点到双链表的头部
// 插入节点到双链表的尾部
// 插入节点到指定位置
(DoublyLinkedList *)insertAtPosition:(int)position:(Node *)node {// 检查位置是否合法if (position < 0 || position > self.count) {return self;}
Node *currentNode = self.head;for (int i = 0; i < position; i++) {currentNode = currentNode.next;}
currentNode.next = node;node.previous = currentNode;node.next = currentNode.next;currentNode.next = node;
return self;}
// 删除节点
(DoublyLinkedList *)deleteNode:(Node *)node {if (node.previous) {node.previous.next = node.next;}if (node.next) {node.next.previous = node.previous;}
if (node == self.head) {self.head = node.next;}if (node == self.tail) {self.tail = node.previous;}
return self;}
// 删除指定位置的节点
(DoublyLinkedList *)deleteAtPosition:(int)position {Node *currentNode = self.head;for (int i = 0; i < position; i++) {currentNode = currentNode.next;}
Node *nodeToDel = currentNode.next;currentNode.next = nodeToDel.next;nodeToDel.next = nil;
if (nodeToDel == self.tail) {self.tail = currentNode;}
return self;}
// 遍历双链表
// 计算双链表的节点数量
@end
以上代码实现了一个基本的DoublyLinkedList双链表,支持插入、删除和遍历等基本操作。开发者可以根据实际需求扩展功能,例如增加双链表的反转、清空等操作。
注:上述代码仅为示例,具体实现中可能需要根据实际需求进行调整和优化。
转载地址:http://dinfk.baihongyu.com/