對應力扣,回文鏈表,代碼見下
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:bool isPalindrome(ListNode* head) {list<int> li;ListNode *tmp = head;while(tmp){li.push_back(tmp->val);tmp = tmp->next;}for(list<int>::reverse_iterator it = li.rbegin(); it != li.rend(); it++){if((*it)!= head->val){return false;}head = head -> next;}return true;}
};
有序集合set的特點:容器內的元素不重復、每插入一個元素,容器內的元素都會進行有序排列。
還有另外一種mutiset:容器內的元素可以重復、每插入一個元素,容器內的元素都會進行有序排序。
容器特點:線性容器(vector、string、list),樹形容器(set、multiset)
set對象創建,代碼見下
#include<iostream>
#include<set>using namespace std;void printSet(const set<int>& s) {for (set<int>::const_iterator it = s.begin(); it != s.end(); it++) {cout << *it << " ";}cout << endl;
}int main() {// 1 默認構造函數set<int> s1;cout << "s1: ";printSet(s1);// 2 初始化列表set<int> s2_1 = { 5, 4, 9, 3, 2, 1 };cout << "s2_1: ";printSet(s2_1);set<int> s2_2 = { 9, 8, 7, 7, 6, 5 };cout << "s2_2: ";printSet(s2_2);// 3 迭代器方式set<int> s3 = {s2_1.begin(), s2_1.end()};cout << "s3: ";printSet(s3);// 4 拷貝構造set<int> s4(s3);cout << "s4: ";printSet(s4);return 0;
}
set賦值操作,代碼見下
#include<iostream>
#include<set>using namespace std;void printSet(const set<int>& s) {for (set<int>::const_iterator it = s.begin(); it != s.end(); it++) {cout << *it << " ";}cout << endl;
}int main() {set<int> s = { 9, 8, 4, 3, 1, 2 };cout << "s: ";printSet(s);// 1 = set對象set<int> s1;s1 = s;cout << "s1: ";printSet(s1);// 2 = 初始化列表set<int> s2;s2 = { 3, 5, 4 };cout << "s2: ";printSet(s2);return 0;
}
list大小操作,代碼見下
#include<iostream>
#include<set>using namespace std;void printSet(const set<int>& s) {for (set<int>::const_iterator it = s.begin(); it != s.end(); it++) {cout << *it << " ";}cout << endl;
}int main() {set<int> s = { 9, 8, 4, 3, 1, 2 };cout << "s.enpty(): " << s.empty() << endl;cout << "s.size(): " << s.size() << endl;return 0;
}