zoukankan      html  css  js  c++  java
  • 数据结构<二>双向链表

    #include<iostream>
    using namespace std;
    struct Node{
      int data;
      Node* prev;
      Node* next;
    };
    class List{
      private:
        Node* head;
      public:
        List();
        ~List();
        int Length();
        bool Empty();
        void clear();
        void push_front(int x);
        void push_back(int x);
        void pop_front();
        void pop_back();
        void print();     
    };
    List::List(){
      head = new Node;
      head->prev = head->next = head;
    }
    List::~List(){
      clear();
      delete head;
    }
    int List::Length(){
      Node *q = head->next;
      int k = 0;
      while (q != head) {
        k++;
        q = q->next;
      }
      return k;
    }
    bool List::Empty(){
      return head->next == head;
    }
    void List::push_front(int x){
      Node* q = new Node;
      q->data = x;
      q->prev = head;
      q->next = head->next;
      head->next->prev = q;
      head->next = q;
    }
    void List::push_back(int x){
      Node* q = new Node;
      q->data = x;
      q->prev = head->prev;
      q->next = head;
      head->prev->next = q;
      head->prev = q;
    }
    void List::pop_front(){
      if (Empty()) return ;
      Node *q = head->next;
      head->next = q->next;
      q->next->prev = head;
      delete q;
    }
    void List::pop_back(){
      if (Empty()) return ;
      Node *q = head->prev;
      head->prev = q->prev;
      q->prev->next = head;
      delete q;
    }
    void List::clear() {
      Node *p = head->next; 
      while(p != head) {
        Node *q = p; 
        p = p->next; 
        delete q; 
      } 
      head->next = head;
      head->prev = head;
    }
    void List::print() {
      Node *q = head->next;
      while (q != head) {
        cout<<q->data<<" ";
        q = q->next; 
      }
      cout<<endl;
    }
    int main() {
      List l;
      l.push_back(2);  
      l.push_front(3);  
      l.push_back(4);
      l.push_front(5);
      l.push_back(6);
      l.pop_front();
      l.print();
      cout<<l.Length()<<endl;
      return 0;
    }
  • 相关阅读:
    移动web开发之flex布局(弹性布局)
    移动web开发之流式布局
    移动端基础
    3D变形(CSS3) transform
    动画(CSS3) animation
    2D变形(CSS3) transform
    过渡(CSS3)
    CSS精灵技术(sprite)
    字体图标
    伸缩布局(CSS3)
  • 原文地址:https://www.cnblogs.com/a863886199/p/7554087.html
Copyright © 2011-2022 走看看