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

后端 未结 10 1242
栀梦
栀梦 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: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
    

提交回复
热议问题