栈、队列iOS实现方案-纸牌游戏 小猫钓鱼

假如游戏开始时,小哼手中有6张牌,顺序为 2 4 1 2 5 6 ,小哈手中有6张牌,顺序为3 1 3 5 6 4,最终谁会获胜呢?

//
//  main.m
//  Algorithms
//
//  Created by yuki on 2017/3/25.
//  Copyright © 2017年 kang.yu.sh. All rights reserved.
//

#import 
static NSMutableArray *queue1;
static NSMutableArray *queue2;
static NSMutableArray *stack;

void AddRemoveQueue(NSMutableArray *queue) {
    NSString *head = queue[0];
    BOOL isFind = NO;
    NSMutableArray *currentList = [NSMutableArray arrayWithCapacity:50];
    for (NSInteger j = stack.count-1; j >= 0 ; j--) {//收回桌面上牌
        [currentList addObject:stack[j]];
        if ([stack[j] isEqualToString:head]) {
            isFind = YES;
            break;
        }
    }
    if (isFind) {
        [stack removeObjectsInArray:currentList];
        [queue addObject:head];
        [queue addObjectsFromArray:currentList];
    }
    else{
        [stack addObject:head];
    }
    [queue removeObjectAtIndex:0];
}

void sumalute(){
    while (YES){
        if (queue1.count == 0) {//Q1没牌了
            for (NSInteger j = stack.count-1; j >= 0 ; j--) {
                [queue2 addObject:stack[j]];
            }
            [stack removeAllObjects];
            break;
        }
        if (queue2.count == 0) {//Q2没牌了
            for (NSInteger j = stack.count-1; j >= 0 ; j--) {
                [queue1 addObject:stack[j]];
            }
            [stack removeAllObjects];
            break;
        }

        AddRemoveQueue(queue1);
        NSLog(@"*********Queue1*********");
        NSLog(@"queue1>>>: %@, stack>>>: %@", queue1, stack);
        AddRemoveQueue(queue2);
        NSLog(@"*********Queue2*********");
        NSLog(@"queue2>>>: %@, stack>>>: %@", queue2, stack);
    }
    
    NSLog(@"******************");
    NSLog(@"queue1>>>: %@", queue1);
    NSLog(@"queue2>>>: %@", queue2);
    NSLog(@"stack >>>: %@", stack);
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        queue1 = [NSMutableArray arrayWithCapacity:100];
        [queue1 addObjectsFromArray:[NSArray arrayWithObjects:@"2",@"4",@"1",@"2",@"5",@"6", nil]];
        queue2 = [NSMutableArray arrayWithCapacity:100];
        [queue2 addObjectsFromArray:[NSArray arrayWithObjects:@"3",@"1",@"3",@"5",@"6",@"4", nil]];
        stack = [NSMutableArray arrayWithCapacity:100];
        
        sumalute();
    }
    return 0;
}


你可能感兴趣的:(栈、队列iOS实现方案-纸牌游戏 小猫钓鱼)