// Bidirectional loop list
Typedef struct dnode
{
Int data;
Struct dnode * preNode, * nextNode;
} DCycleLink;
Two operations are completed:
1 insert dCycleLink * insertData (dCycleLink * head, int num, int data );
2. Delete dCycleLink * deleteData (dCycleLink * head, int data );
In fact, the operation of the bidirectional loop list is similar to that of the unidirectional loop list. You only need to consider an element like prenode. Okay, go to the code
1 insert
// Find the node;
DCycleLink * insertData (dCycleLink * head, int num, int data)
{
Assert (head! = NULL );
DCycleLink * p = head;
Int count = 1;
While (p! = NULL & count <num)
{
Count ++;
P = p-> nextNode;
}
If (count = num)
{
DCycleLink * s = (dCycleLink *) malloc (sizeof (dCycleLink ));
If (s! = NULL & p! = NULL)
{
S-> data = data;
S-> preNode = p; // 1
P-> nextNode-> preNode = s; // 2
S-> nextNode = p-> nextNode; // 3
P-> nextNode = s; // 4
}
Cout <"inserted successfully !!! "<Endl;
Printcancelink (head );
}
Else
{
Cout <"insertion failed !!! "<Endl;
}
Return head;
}
2. Delete
DCycleLink * deleteData (dCycleLink * head, int data)
{
Assert (head );
DCycleLink * p = head;
While (p! = NULL & p-> data! = Data)
{
P = p-> nextNode;
}
// Skip the loop: 1 p is NULL and 2 p-> data = data is not found. The result is found.
If (p-> data = data)
{
P-> preNode-> nextNode = p-> nextNode;
P-> nextNode-> preNode = p-> preNode;
Free (p );
P = NULL;
Cout <"found. Deleted successfully! "<Endl;
Printcancelink (head );
}
Else
{
Cout <"Not found. deletion failed! "<Endl;
}
Return head;
}
3 test code
Int main ()
{
Int num;
Cout <"Enter the number of nodes to be created n :";
Cin> num;
DCycleLink * cycleLink;
Cancelink = createdoublycancelink (num );
Cancelink = insertData (cancelink, 2, 10 );
Cancelink = deleteData (cancelink, 2 );
Return 0;
}
DCycleLink * createDoublyCycleLink (int n)
{
Int xValue;
DCycleLink * head, * p, * pre;
Cout <"enter 1st numbers :";
Cin> xValue;
P = (dCycleLink *) malloc (sizeof (dCycleLink ));
P-> data = xValue;
P-> preNode = NULL;
P-> nextNode = NULL;
Head = p;
Pre = p;
For (int I = 1; I <n; I ++)
{
Cout <"Enter the" <I + 1 <"digit :";
Cin> xValue;
P = (dCycleLink *) malloc (sizeof (dCycleLink ));
P-> data = xValue;
P-> nextNode = NULL;
P-> preNode = pre; // bidirectional Characteristics
Pre-> nextNode = p;
Pre = p;
}
Printcancelink (head );
Return head;
}
Void printcancelink (dashelink * head)
{
DCycleLink * pNode = head;
Cout <"the data in this linked list is:" <endl;
While (pNode)
{
Cout <pNode-> data <endl;
PNode = pNode-> nextNode;
}
}