[Cpp]
# Include <iostream. h>
// Define the node (Data Object) Interface
Class Node
{
// Declare the list class as the membership class of this class
Friend class list;
// Private member
Private:
Int Data; // node Data
Node * previous; // forward pointer
Node * next; // successor pointer
};
// Define the interface declaration for the list of two-way linked lists
Class list
{
// Private member
Private:
Node * Head; // The Head pointer of the linked list.
Node * Tail; // The Tail pointer of the linked list
// Define interface functions
Public:
// Constructor
List ();
// Destructor
~ List ();
// Add data from the end of the linked list
Void Build_HT (int Data );
// Add data from the front of the linked list
Void Build_TH (int Data );
// Display data from start to end
Void list: Display_HT ();
// Display data from the end to the header
Void list: Display_TH ();
// Clear all data in the linked list
Void Clear ();
};
// Test the two-way linked list using the main () function
Int main (void)
{
List list1;
Int I;
// Add data from the end
Cout <"Add to the back of the list1:" <endl;
For (I = 1; I <= 20; I = I + 2 ){
List1.Build _ HT (I );
Cout <I <"";
}
Cout <endl;
// Add data from scratch
Cout <"Add to the front of the list1:" <endl;
For (I = 0; I <= 20; I = I + 2 ){
List1.Build _ TH (I );
Cout <I <"";
}
Cout <endl;
// Display the linked list
List1.Display _ HT ();
List1.Display _ TH ();
Return 0;
}
// List Function Definition
// Constructor Definition
List: list ()
{
// Initial Value
Head = 0;
Tail = 0;
}
// Destructor Definition
List ::~ List ()
{
Clear ();
}
// Add data from the end of the linked list
Void list: Build_HT (int Data)
{
Node * Buffer;
Buffer = new Node;
Buffer-> Data = Data;
If (Head = 0)
{
Head = Buffer;
Head-> next = 0;
Head-> previous = 0;
Tail = Head;
}
Else
{
Tail-> next = Buffer;
Buffer-> previous = Tail;
Buffer-> next = 0;
Tail = Buffer;
}
}
// Add data from the front of the linked list
Void list: Build_TH (int Data)
{
Node * NewNode;
NewNode = new Node;
NewNode-> Data = Data;
If (Tail = 0)
{
Tail = NewNode;
Tail-> next = 0;
Tail-> previous = 0;
Head = Tail;
}
Else
{
NewNode-> previous = 0;
NewNode-> next = Head;
Head-> previous = NewNode;
Head = NewNode;
}
}
// Display data from start to end
Void list: Display_HT ()
{
Node * TEMP;
TEMP = Head;
Cout <"Display the list from Head to Tail:" <endl;
While (TEMP! = 0)
{
Cout <TEMP-> Data <"";
TEMP = TEMP-> next;
}
Cout <endl;
}
// Display data from the end to the header
Void list: Display_TH ()
{
Node * TEMP;
TEMP = Tail;
Cout <"Display the list from Tail to Head:" <endl;
While (TEMP! = 0)
{
Cout <TEMP-> Data <"";
TEMP = TEMP-> previous;
}
Cout <endl;
}
// Clear all data in the linked list
Void list: Clear ()
{
Node * Temp_head = Head;
If (Temp_head = 0) return;
Do
{
Node * TEMP_NODE = Temp_head;
Temp_head = Temp_head-> next;
Delete TEMP_NODE;
}
While (Temp_head! = 0 );
}