Python算法入门——第2章 1,队列

有一串经过加密的数字需要解密。解密规则是这样的:首先将第 1 个数删除,紧接着将第 2 个数放到这串数的末尾,再将第 3 个数删除并将第 4 个数放到这串数的末尾,再将第 5 个数删除……直到剩下最后一个数,将最后一个数也删除。
 

class Solution():
    '''
    去除重复数字
    从大到小排序
    '''
    def DuiLie(self, x):
        #将字符串列表化,便于进行append操作
        queue = [i for i in x]
        a = list()        
        head,tail = 1,len(queue)        
        while head < tail:
            queue.append(queue[head])
            head += 2
            
        for i in range(len(queue)):
            if i % 2 == 0:
                a.append(queue[i])
        return a

if __name__ == "__main__":
    a = Solution()
    print(a.DuiLie('631758924'))

下面是c语言代码

#include <stdio.h>
int main()
{
    int q[102]={0,6,3,1,7,5,8,9,2,4},head,tail;
    int i;
    //初始化队列
    head=1;
    tail=10; //队列中已经有9个元素了, tail指向队尾的后一个位置
    while(head<tail) //当队列不为空的时候执行循环
    {
        //打印队首并将队首出队
        printf("%d ",q[head]);
        head++;
        //先将新队首的数添加到队尾
        q[tail]=q[head];
        tail++;
        //再将队首出队
        head++;
    }
    getchar();getchar();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lpp5406813053/article/details/83627015
今日推荐