用objective c 生成循环队列
时间: 2024-05-10 22:18:38 浏览: 122
C语言实现循环队列
下面是一个使用 Objective-C 实现的循环队列示例代码:
```
@interface CircularQueue : NSObject
- (instancetype)initWithCapacity:(NSUInteger)capacity;
- (BOOL)isEmpty;
- (BOOL)isFull;
- (NSUInteger)size;
- (void)enqueue:(id)object;
- (id)dequeue;
- (id)front;
- (id)rear;
@end
@implementation CircularQueue {
NSUInteger _capacity;
NSUInteger _head;
NSUInteger _tail;
NSMutableArray *_data;
}
- (instancetype)initWithCapacity:(NSUInteger)capacity {
self = [super init];
if (self) {
_capacity = capacity;
_head = 0;
_tail = 0;
_data = [NSMutableArray arrayWithCapacity:capacity];
}
return self;
}
- (BOOL)isEmpty {
return _head == _tail;
}
- (BOOL)isFull {
return (_tail + 1) % _capacity == _head;
}
- (NSUInteger)size {
return (_tail - _head + _capacity) % _capacity;
}
- (void)enqueue:(id)object {
if ([self isFull]) {
NSLog(@"Queue is full");
return;
}
[_data addObject:object];
_tail = (_tail + 1) % _capacity;
}
- (id)dequeue {
if ([self isEmpty]) {
NSLog(@"Queue is empty");
return nil;
}
id object = [_data objectAtIndex:_head];
[_data removeObjectAtIndex:_head];
_tail = (_tail - 1 + _capacity) % _capacity;
return object;
}
- (id)front {
if ([self isEmpty]) {
NSLog(@"Queue is empty");
return nil;
}
return [_data objectAtIndex:_head];
}
- (id)rear {
if ([self isEmpty]) {
NSLog(@"Queue is empty");
return nil;
}
return [_data objectAtIndex:_tail - 1];
}
@end
```
使用示例:
```
CircularQueue *queue = [[CircularQueue alloc] initWithCapacity:5];
[queue enqueue:@1];
[queue enqueue:@2];
[queue enqueue:@3];
NSLog(@"%@", [queue front]); // Output: 1
NSLog(@"%@", [queue rear]); // Output: 3
[queue dequeue];
NSLog(@"%@", [queue front]); // Output: 2
NSLog(@"%@", [queue rear]); // Output: 3
```
阅读全文