zoukankan      html  css  js  c++  java
  • List双向链表容器

      list 容器实现了双向链表的数据结构,数据元素是通过链表指针串连成逻辑意义上的线 性表,这样,对链表的任一位置的元素进行插入、删除和查找都是极快速的。

    图 2-7 是 list 采用的双向循环链表的结构示意图。

     由于 list 对象的节点并不要求在一段连续的内存中,所以,对于迭代器,只能通过“++” 或“- -”的操作将迭代器移动到后继/前驱节点元素处。而不能对迭代器进行+n 或-n 的操 作,这点,是与 vector 等不同的地方

    代码如下:

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<list>
     4 using namespace std;
     5 int main(){
     6     //创建空链表
     7     list<int> l;
     8     //创建具有n个元素的链表
     9     list<int> l1(10);//创建具有10个元素的链表
    10     //三种方法插入新的元素
    11     //采用push_back()方法往尾部插入新元素,链表自动扩张。
    12     //采用push_front()方法往首部插入新元素,链表自动扩张
    13     //采用insert()方法往迭代器位置处插入新元素,链表自动扩张。
    14     //迭代器只能“++”或“--”操作,不能进行+n或-n操作
    15     //链表尾部插入新元素 
    16     l.push_back(2);
    17     l.push_back(1);
    18     l.push_back(5);
    19     //链表头部插入新元素 
    20     l.push_front(8);
    21     //在任意位置插入新元素
    22     list<int>::iterator it;
    23     it=l.begin();
    24     it++;
    25     l.insert(it,20);
    26     //使用前向迭代器遍历链表
    27     list<int>::iterator it1;
    28     for(it1=l.begin();it1!=l.end();it1++){
    29         cout<<*it1<<" ";
    30     } 
    31     cout<<endl;
    32     //反向遍历用反向迭代器reverse_iterator
    33     list<int>::reverse_iterator rit;
    34     for(rit=l.rbegin();rit!=l.rend();rit++){
    35         cout<<*rit<<" ";
    36     } 
    37     cout<<endl;
    38     //可以使用remove()方法删除链表中一个元素,值相同的元素都会被删除。
    39     l.remove(1);
    40     //使用pop_front()方法删除链表首元素,使用pop_back()方法删除表尾元素。
    41     l.pop_front();
    42     l.pop_back();
    43     //使用erase()方法删除迭代器位置上的元素。
    44     list<int>::iterator it2;
    45     it2=l.begin();
    46     it2++;
    47     l.erase(it2);
    48     //元素查找,返回迭代器的位置,没有找到,返回end()的位置
    49     list<int>::iterator it3;
    50     it3=find(l.begin(),l.end(),5);
    51     if(it3!=l.end()){
    52         cout<<"find it"<<endl;
    53     }
    54     else
    55     {
    56         cout<<"not find it"<<endl;
    57     }
    58     //元素排序sort()
    59     l.sort();
    60     //剔除重复元素unique(),只保留一个
    61     l.unique(); 
    62     //清空链表,clear()
    63     l.clear(); 
    64     return 0;
    65 }
  • 相关阅读:
    Java并发容器和线程池
    CountDownLatch、CyclicBarrier
    spring data jpa
    转换时间的工具类(1)
    swagger 报错: TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot h
    自动生成entry-mapper-service-controller
    Hutool工具包导出Excel文件异常 You need to add dependency of poi-ooxml to your project
    Java获取24小时制的时间方法
    查询全国城市行政区
    Java对象与Json字符串之间的转化
  • 原文地址:https://www.cnblogs.com/zjl192628928/p/9266595.html
Copyright © 2011-2022 走看看