使用双端队列模拟动态数组的部分功能

C语言作为一门古老的语言,在系统级,高性能的领域依然独领风骚,但有些时候,使用起来总是没那么顺手。

比如数组。这里使用双端队列简单的实现了一些类似动态数组的功能。

模拟 stack, queue 实现 push, pop, shift, unshift 操作,以及两个遍历方法,for_each() 和 map(),其中 for_each 接受一个函数,函数包括一个 item 参数,map 方法与其类似,但是返回一个数组。

Double Queue 定义:

typedef int data;
typedef struct node* node;
typedef struct double_queue* dqueue;
struct node {
  data item;
  node prev, next;
};
struct double_queue {
  int count;
  node head, tail;
};

Push

void dq_push(dqueue dq, data item) {
  node t = malloc(sizeof *t);
  t->item = item;
  t->prev = dq->tail;
  t->next = NULL;
  if (dq->count) {
    dq->tail->next = t;
  } else {
    dq->head = t;
  }
  dq->tail= t;
  dq->count++;
}

pop

shift

unshift

遍历操作:

for_each

map

完整源代码及测试用例:

Last updated