How do I make and use a Queue in Objective-C?

后端 未结 10 1212
栀梦
栀梦 2020-11-27 10:21

I want to use a queue data structure in my Objective-C program. In C++ I\'d use the STL queue. What is the equivalent data structure in Objective-C? How do I push/pop ite

相关标签:
10条回答
  • 2020-11-27 10:49

    As far as I know, Objective-C does not provide a Queue data structure. Your best bet is to create an NSMutableArray, and then use [array lastObject], [array removeLastObject] to fetch the item, and [array insertObject:o atIndex:0]...

    If you're doing this a lot, you might want to create an Objective-C category to extend the functionality of the NSMutableArray class. Categories allow you to dynamically add functions to existing classes (even the ones you don't have the source for) - you could make a queue one like this:

    (NOTE: This code is actually for a stack, not a queue. See comments below)

    @interface NSMutableArray (QueueAdditions)
    
    - (id)pop;
    - (void)push:(id)obj;
    
    @end
    
    @implementation NSMutableArray (QueueAdditions)
    
    - (id)pop
    {
        // nil if [self count] == 0
        id lastObject = [[[self lastObject] retain] autorelease];
        if (lastObject)
            [self removeLastObject];
        return lastObject;
    }
    
    - (void)push:(id)obj
    {
         [self addObject: obj];
    }
    
    @end
    
    0 讨论(0)
  • 2020-11-27 10:50

    re:Wolfcow -- Here is a corrected implementation of Wolfcow's dequeue method

    - (id)dequeue {
        if ([self count] == 0) {
            return nil;
        }
        id queueObject = [[[self objectAtIndex:0] retain] autorelease];
        [self removeObjectAtIndex:0];
        return queueObject;
    }
    
    0 讨论(0)
  • 2020-11-27 10:50

    Use NSMutableArray.

    0 讨论(0)
  • 2020-11-27 10:51

    this is my implementation, hope it helps.

    Is kind of minimalistic, so you must keep the track of the head by saving the new head at pop and discarding the old head

    @interface Queue : NSObject {
        id _data;
        Queue *tail;
    }
    
    -(id) initWithData:(id) data;
    -(id) getData;
    
    -(Queue*) pop;
    -(void) push:(id) data;
    
    @end
    
    #import "Queue.h"
    
    @implementation Queue
    
    -(id) initWithData:(id) data {
        if (self=[super init]) {
            _data = data;
            [_data retain];
        }
        return self;
    }
    -(id) getData {
        return _data;
    }
    
    -(Queue*) pop {
        return tail;
    }
    -(void) push:(id) data{
        if (tail) {
            [tail push:data];
        } else {
            tail = [[Queue alloc]initWithData:data];
        }
    }
    
    -(void) dealloc {
        if (_data) {
            [_data release];
        }
        [super release];
    }
    
    @end
    
    0 讨论(0)
提交回复
热议问题