這是一個題目,但是后期出題者又說一個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;
}
十分感謝!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/67713.html
標籤:C++ 語言
