As shown in the diagram, the Single chain table node has two fields: the pointer field and the data field are defined as follows:
typedef int DATATYPE;
Class Node {
friend class NodeList;
Private:
dataType data; Data domain
node* link; Pointer field A pointer to the next element
};
Also has a node-linked list for storing data: defined as follows
Class NodeList {
private:
node* first; Head node pointer public
:
nodeList () {first = 0;}
void Add (DataType num); Add
void Inserttail (DataType num) sequentially from the head of the list; Connection to tail
void Mediuminsert (dataType num, int pos);
void Delete (DataType num); Delete a value
void Show ();
};
Traverse the entire list through the pointer:
void Nodelist::show () {
node* P = new node ();
p = First; Point to the first node while
(P! = NULL) {
DataType temp = p->data;
cout << temp << " ";
p = p->link; Data Iteration
}
cout << Endl;
}
Add a new node:
void Nodelist::add (DataType num) {
node* NewNode = new node (); Create a new node
newnode->data = num;
Newnode->link = First; The pointer field of the new node points to the next node first
= NewNode; New node marked as head node
}
Insert to Trailer:
void Nodelist::inserttail (DataType num) {
///new node
node* newNode = "n" ();
Newnode->data = num;
Used to traverse
node* p = new node ();
p = First;
while (p->link! = NULL) {
p = p->link;
}
Newnode->link = p->link; Tail Insertion method
P->link = NewNode;
}
There is no difference between intermediate and trailing inserts just iterate to the specified location and insert the operation
interpolation
void Nodelist::mediuminsert (dataType num, int pos) {
node* NewNode = new node ();
Newnode->data = num;
node* p = new node ();
p = First;
int k = 1; Mark Node Location
while (p->link! = NULL && K < pos-1) {
p = p->link;
k++;
}
Newnode->link = p->link;
P->link = NewNode;
}
Delete operation:
void NodeList::D elete (DataType num) {
node* P = new node (); The first pointer
node* q = new node (); The second pointer
p = first;
Q = NULL;
if (p = = NULL) {
return;
}
if (p->data = = num) { //determine if the first node is the node to be deleted.
Delete p; Delete node
return;
}
else {
//start traversing
while (P! = NULL) {
q = p;
q = q->link;
if (q->data = = num) {
P->link = q->link;
Delete q;
break;
}
p = p->link;
}}}