在iOS开发中,可以使用Objective-C或者Swift来实现循环链表。以下是一个简单的Objective-C实现: 首先,定义一个节点类: ```objective-c @interface ListNode : NSObject @property (nonatomic, strong) id data; @property (nonatomic, strong) ListNode *next; @end ``` 然后,定义一个链表类: ```objective-c @interface LinkedList : NSObject @property (nonatomic, strong) ListNode *head; @property (nonatomic, assign) NSInteger length; - (void)addNode:(id)data; - (void)removeNode:(id)data; - (void)insertNode:(id)data atIndex:(NSInteger)index; - (void)printList; @end ``` 以下是链表类的实现: ```objective-c @implementation LinkedList { ListNode *tail; } - (instancetype)init { self = [super init]; if (self) { head = tail = [[ListNode alloc] init]; } return self; } - (void)addNode:(id)data { ListNode *node = [[ListNode alloc] init]; node.data = data; node.next = head.next; head.next = node; tail = node; length++; } - (void)removeNode:(id)data { ListNode *current = head.next; ListNode *previous = head; while (current != nil) { if ([current.data isEqual:data]) { previous.next = current.next; if (current == tail) { tail = previous; } length--; return; } previous = current; current = current.next; } } - (void)insertNode:(id)data atIndex:(NSInteger)index { if (index < 0 || index > length) { return; } ListNode *newNode = [[ListNode alloc] init]; newNode.data = data; if (index == 0) { newNode.next = head.next; head.next = newNode; if (length == 1) { tail = newNode; } } else { ListNode *current = head.next; for (NSInteger i = 0; i < index - 1; i++) { current = current.next; } newNode.next = current.next; current.next = newNode; if (index == length) { tail = newNode; } } length++; } - (void)printList { ListNode *current = head.next; while (current != head) { NSLog(@"%@", current.data); current = current.next; } NSLog(@"%@", current.data); } @end ``` 这样,你就可以在Objective-C中实现循环链表了。 [2023-11-08 00:29:01 | AI问答 | 564点数解答]