用数组实现栈(Stacks)、队列(Queue)和双向链表(Doubly Linked List)的伪代码

具体解释来自《挑战程序设计竞赛2:算法和数据结构》,其它预备知识内容请自行查询维基百科。

用数组实现栈(Stacks)、队列(Queue)和双向链表(Doubly Linked List)的伪代码

栈(Stacks)

/*Program-4.1 用数组实现栈*/

initalize()
    top=0;

isEmpty()
    return top==0;
    
isFull()
    return top>=MAX-1;
    
push(x)
    if isFull()
        error;
    top++;
    S[top]=x;
    
pop()
    if isEmpty()
        error;
    top--;
    return S[top+1];

队列(Queue)

/*Program-4.2 用数组实现队列*/

initalize()
    head=tail=0;

isEmpty()
    return head==tail;
    
isFull()
    return head==(tail+1)%MAX;
    
enqueue(x)
    if isFull()
        error;
    Q[tail]=x;
    if tail+1==MAX
        tail=0;
    else
        tail++;
    
dequeue()
    if isEmpty()
        error;
    x=Q[head];
    if head+1==MAX;
        head=0;
    else
        head++;
    return x;

双向链表(Doubly Linked LIst)

/*Program-4.2 用数组实现队列*/

//结点
struct Node{
    int key;
    Node *prev,*next;
};

//初始化
Node *nil;

void init(){
    nil=(Node *)malloc(sizeof(Node));
    nil->next=nil;
    nil->prev=nil;
}

//插入元素
void insert(int key){
    Node *x=(Node *)malloc(size(Node));
    x->key=key;
    x->next=nil->next;
    nil->next->prev=x;
    nil->next=x;
    x->prev=nil;
}

//搜索元素
Node* listSearch(int key){
    Node *cur=nil->next;
    while(cur!=nil&&cur->key!=key){
        cur=cur->next;
    }
    return cur;
}

//删除元素
void deleteNode(Node *t){
    if(t==nil) return;
    t->prev->next=t->next;
    t->next->prev=t->prev;
    free(t);
}

void deleteFirst(){
    deleteNode(nil->next);
}

void deleteLast(){
    deleteNode(nil->prev);
}

void deleteKey(int key){
    deleteNode(listSearch(key));
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值