C++ list数据删除、list数据访问、list反转链表、list数据排序

发布于:2025-06-04 ⋅ 阅读:(24) ⋅ 点赞:(0)

list数据删除,代码见下

#include<iostream>
#include<list>

using namespace std;

void printList(const list<int>& l) {
	for (list<int>::const_iterator it = l.begin(); it != l.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;
}

/*
1 pop_front
2 pop_back
3 erase clear
*/

int main() {
	list<int> l = { -1, 3, 4, 7, 9, -1 };
	l.pop_back();
	printList(l);
	l.pop_front();
	printList(l);

	list<int>::iterator it = l.erase(l.begin());
	printList(l);
	cout << *it << endl;
	it = l.erase(it);
	printList(l);
	cout << *it << endl;

	it++;
	it++;
	l.erase(it, l.end());
	printList(l);

	l.clear();
	printList(l);

	cout << "l.size()= " << l.size() << endl;
	return 0;
}

结果见下,助理解

-1 3 4 7 9
3 4 7 9
4 7 9
4
7 9
7
7 9

l.size()= 0

list数据访问,代码见下

#include<iostream>
#include<list>

using namespace std;

void printList(const list<int>& l) {
	for (list<int>::const_iterator it = l.begin(); it != l.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;
}

int getListItemByIndex(list<int>& l, int index) {
	list<int>::iterator it = l.begin();
	while (index) {
		it++;
		index--;
	}
	return *it;
}


int main() {
	list<int> l = { -1, 2, 1, 3, 4, 7, 9, -1 };
	
	list<int>::iterator it = l.begin();
	cout << getListItemByIndex(l, 4);
	return 0;
}

list反转列表,代码见下,直接找的内部源码

    void reverse() noexcept { // reverse sequence
        const _Nodeptr _Phead = _Mypair._Myval2._Myhead;
        _Nodeptr _Pnode       = _Phead;

        for (;;) { // flip pointers in a node
            const _Nodeptr _Pnext = _Pnode->_Next;
            _Pnode->_Next         = _Pnode->_Prev;
            _Pnode->_Prev         = _Pnext;

            if (_Pnext == _Phead) {
                break;
            }

            _Pnode = _Pnext;
        }
    }

list数据排序,代码见下

#include<iostream>
#include<list>

using namespace std;

void printList(const list<int>& l) {
	for (list<int>::const_iterator it = l.begin(); it != l.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;
}

int cmp(int a, int b) {
	return a > b;
}

int main() {
	list<int> l = { 2, 1, 3, 4, 7, 9 };
	printList(l);
	l.sort(cmp);
	printList(l);
	
	return 0;
}


网站公告

今日签到

点亮在社区的每一天
去签到