小白求助C++建立简单list容器
这是一个题目,但是后期出题者又说一个tail有问题由于实在太菜了所以不会写……
请问可以帮忙补全代码片段吗?大概的意思已经注释了
使得程序运行后有如下输出:
I love c++ very much!
I love c++
I
love
c++
代码现在是这样
#include
#include
using namespace std;
//MyList
template <class T> struct ListNode {
ListNode(const T& _data = T()): pre(0), next(0), data(_data){}
ListNode<T>* pre;
ListNode<T>* next;
T data;
};
template <typename T> class MyList {
private:
typedef ListNode<T> Node;
ListNode<T>* head;
ListNode<T>* tail;
class list_iterator{
private:
Node* ptr;//指向mylist容器中的某个元素的指针
public:
list_iterator(Node* p=nullptr):ptr(p){}
//重载*, ++, --, ->等基本操作
T &operator*() const{
//返回引用 方便通过*it来修改对象
return ptr->data;
}
Node *operator->() const{
//重载->运算符
return ptr;
}
list_iterator &operator++(){
//TODO:迭代器++,使迭代器内置指针向后移动一位
}
list_iterator operator++(int){
//TODO:后置++
}
bool operator==(const list_iterator &t) const{
// TODO:重载==
}
bool operator!=(const list_iterator &t) const{
// TODO:重载!=
}
};
public:
typedef list_iterator iterator;
MyList():head(new Node) {
head->next = head;
head->pre = head;
};
~MyList(){
//Clear();
delete head;
head = NULL;
};
bool empty() { //判断list是否为空
return head->next == head;
}
void push_back(const T& data) { //尾部插入数据
Node* newnode = new Node(data);
if (empty())
{
head->next = newnode;
head->pre = newnode;
newnode->next = head;
newnode->pre = head;
}
else
{
Node* tail = head-> pre;
tail->next = newnode;
newnode->next = head;
newnode->pre = tail;
head->pre = newnode;
}
}
void pop_back() { //删除尾部数据
if (!empty()) {
Node* del = head->pre;
Node* tail = del->pre;
delete del;
tail->next = head;
head->pre = tail;
}
}
void print() { //打印list
if (!empty()) {
Node* cur = head->next;
while (cur!=head) {
cout << cur->data << ' ';
cur = cur->next;
}
cout << endl;
}
}
int size() { //返回list大小
Node* cur = head->next;
int count = 0;
while (cur!=head) {
++count;
cur = cur->next;
}
return count;
}
//迭代器操作方法
iterator begin() const{
//TODO:返回链表头部指针
}
iterator end() const{
//TODO:返回链表尾部指针
}
//其他成员函数 可以自己尝试实现insert/erase
};
int main() {
MyList<string> mylist_str;
mylist_str.push_back("I");
mylist_str.push_back("love");
mylist_str.push_back("c++");
mylist_str.push_back("very");
mylist_str.push_back("much!");
mylist_str.print();
mylist_str.pop_back();
mylist_str.pop_back();
mylist_str.print();
for (MyList<string>::iterator it = mylist_str.begin(); it != mylist_str.end(); it++) {
cout << *it << endl;
}
return 0;
}
十分感谢!