Mn ơi , em vẫn không hiểu rõ tại sao dòng p=p->Getpointer();
hay dòng this->head=this->head->Getpointer();
trong file linkedlist.cpp
là để con trỏ tiến đến phần tử tiếp theo , mn chỉ em với, em cảm ơn !!!
main.cpp
#include <iostream>
#include "linkedlist.h"
using namespace std;
int main()
{
linkedlist *list_=new linkedlist();
element *e;
e=new element(9);
list_->InsertTail(e);
e=new element(10);
list_->InsertTail(e);
e=new element(8);
list_->InsertTail(e);
list_->Travel();
list_->DeleteFirst();
cout<<"\n";
list_->Travel();
return 0;
}
element.h
#ifndef ELEMENT_H
#define ELEMENT_H
class element
{
private:
int data;
element *pointer;
public:
element();
element(int);
virtual ~element();
int Getdata() { return data; }
void Setdata(int val) { data = val; }
element * Getpointer() { return pointer; }
void Setpointer(element* val) { pointer = val; }
protected:
};
#endif // ELEMENT_H
element.cpp
#include "element.h"
element::element()
{
//ctor
this->data=0;
this->pointer=nullptr;
}
element::element(int data)
{
//ctor
this->data=data;
this->pointer=nullptr;
}
element::~element()
{
//dtor
}
linkedlist.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "element.h"
class linkedlist
{
private:
element* head;
element* tail;
int nNum;
public:
linkedlist();
virtual ~linkedlist();
element* Gethead() { return head; }
void Sethead(element* val) { head = val; }
element* Gettail() { return tail; }
void Settail(element* val) { tail = val; }
void InsertFirst(element*);
void InsertTail(element*);
bool DeleteFirst();
void Travel();
protected:
};
#endif // LINKEDLIST_H
linkedlist.cpp
#include "linkedlist.h"
#include <iostream>
using namespace std;
linkedlist::linkedlist()
{
//ctor
this->head=nullptr;
this->tail=nullptr;
this->nNum=0;
}
linkedlist::~linkedlist()
{
//dtor
}
void linkedlist::InsertFirst(element* e){
if(this->head==nullptr)
this->head=this->tail=e;
else{
e->Setpointer(this->head); //step 1
this->head=e; // step 2
}
this->nNum++;
}
void linkedlist::InsertTail(element*e){
if(this->head==nullptr)
this->head=this->tail=e;
else{
this->tail->Setpointer(e);// step 1
this->tail=e; // step 2
}
this->nNum++;
}
void linkedlist::Travel(){
element* p=this->head;
while(p!=nullptr){
cout<<p->Getdata()<<"\t";
p=p->Getpointer();
}
}
bool linkedlist::DeleteFirst(){
if(this->head==nullptr) return false;
else{
element*p=this->head;
this->head=this->head->Getpointer();
delete p;
return true;
}
}