Home > Back-end >  List the main function for a detailed explanation?
List the main function for a detailed explanation?

Time:10-09

 
# include & lt; Iostream>
using namespace std;
Typedef int T;
The class List {
Struct Node {
T data;
Node * next;
The Node (const T& D=(T)), data (d), next (0) {}//zero initial
};
Node * head;//the head pointer, used to hold head node address
Int len.
Public:
The List () : the head (NULL), len (0) {}
Void push_front (const T& D) {//forward
Insert (d, 0);
}
List& Push_back (const T& D) {//stern
Insert (d, size ());
return *this;
}
Int size () const {
Return len.
}
Node * & amp; Getptr (int pos) {//a pointer to the specified location in the list
If (pos<0 | | pos> The size ()) pos=0;
If (pos==0) return the head;
Node * p=head;
for(int i=1; IP=p - & gt; Next;
Return (* p). The next;
}
Void insert (const T& D, int pos) {//at any position insert
Node * & amp; Pn=getptr (pos);
Node * p=new Node (d);
P - & gt; Next=pn;
Pn=p;
+ + len.
}
Void travel (const) {//traversal
Node * p=head;
while(p!=NULL) {
Cout & lt;

P=p - & gt; Next;
}
Cout & lt; }
Void the clear () {//clear the list
while(head!=NULL) {
The Node * p=head - & gt; Next;
//cout & lt; <"Delete" & lt; Delete the head;
The head=p;
}
Len=0;
}
To the List () {
//cout & lt; The clear ();
}
Void erase (int pos) {//effective position of 0 ~ the size () - 1
If (pos<0 | | pos>=the size ()) return;
Node * & amp; Pn=getptr (pos);
Node * p=pn;
Pn=pn - & gt; Next;
The delete p;
-- len;
}
Void the remove (const T& D) {
Int pos.
While ((pos=find (d))!=1)
Erase (pos);
}
Int the find (const T& D) const {
int pos=0;
Node * p=head;
While (p) {
If (p - & gt; data=https://bbs.csdn.net/topics/=d) return pos;
P=p - & gt; Next; + + pos.
}
return -1;
}
Void the set (int pos, const T& D) {
If (pos<0 | | pos>=the size ()) return;
Getptr (pos) - & gt; Data=https://bbs.csdn.net/topics/d;
}
Const bool empty () {return head==NULL; }
T the front (const) {if (empty ()) throw "empty"; Return the head - & gt; The data; }
T the back () const {
If (empty ()) throw "empty";
Node * p=head;
While (p - & gt; Next!=NULL)
P=p - & gt; Next;
The return p - & gt; The data;
}
};

  • Related