zoukankan      html  css  js  c++  java
  • 自己写deque

    //deque
    /*
    what is a deque?
    In Chinese, it's called "双端队列".
    It's different from a queue.
    Its elements can be added to or removed from either the front(head) or back(tail) ,called a head-tail linked list.
    
    输入限制deque
    An input-restricted deque is one where deletion can be made from both ends, but insertion can be made at one end only.
    
    输出限制deque
    An output-restricted deque is one where insertion can be made at both ends, but deletion can be made from one end only
    
    Queue and stack can be considered spectalizations of deques.
    There are at least two common ways to efficiently implement a deque: with a modified dynamic arry or with a doubly linked list
    C++
    
    dq1.push_back(x)    insert element at back
    dq1.push_front(x)    insert element at front
    dq1.pop_back(x)      remove last element
    dq1.pop_front(x)      remove first element
    dq1.back()              return last element
    dq1.front()              return first element
    */
    
    //自己写deque
    //double linked list版 template<typename Object> class Dequeue { private: struct Node { Object data; Node* next; Node* prev; Node(const Object& d = Object(), Node *p = NULL, Node *n = NULL) :data(d), next(n), prev(p){} }; public: Dequeue() { init(); } Dequeue(const Dequeue& q) { init(); *this = q; } const Dequeue& operator=(const Dequeue& q) { if (this == &q) return *this; clear(); Node *p = q.head->next; while (p->next != q.tail) { this.push_back(p->data); p = p->next; } return *this; } ~Dequeue() { clear(); delete head; delete tail; } //判空 bool isEmpty() { return size == 0; } //push_back void push_back(Object item) { size++; Node* p = new Node; p->data = item; Node* q = tail->prev; p->next = tail; p->prev = q; q->next = p; tail->prev = p; } //push_front void push_front(Object item) { size++; Node* p = new Node; p->data = item; Node* q = head->next; p->next = q; p->prev = head; head->next = p; q->prev = p; } //pop_back void pop_back() { size--; Node*p = tail->prev; Node*q = p->prev; q->next = tail; tail->prev = q; delete p; } //pop_front void pop_front() { size--; Node *p = head->next; Node *q = p->next; head->next = q; q->prev = head; delete p; } //back Object back() { return tail->prev->data; } //front Object front() { return head->next->data; } //clear void clear() { while (!isEmpty()) { pop_back(); } } //getsize int getSize() { return size; } private: Node* head; Node* tail; int size; void init() { head = new Node; tail = new Node; size = 0; head->next = tail; tail->prev = head; } };

      

  • 相关阅读:
    ps入门之photoshop文件操作-打开与存储认识 (PS界面介绍)如何新建文档(03)
    ps入门之ps的工作界面的认识学习(界面介绍)界面的组成(02)
    markdown编辑器Typora
    5FAE8F6F96C59ED1字体
    清除浮动float (:after方法)
    SQL中Truncate的用法
    复合索引
    RESTful API 设计指南
    两种js方法发起微信支付:WeixinJSBridge,wx.chooseWXPay区别
    nuxt.js 简述
  • 原文地址:https://www.cnblogs.com/KennyRom/p/5967550.html
Copyright © 2011-2022 走看看