Recently, a linked list is written in reverse order.AlgorithmIt's good to be hands-on.
CodeIt is relatively simple. I will not introduce it as follows:
Code
// Linkreverse. cpp: defines the entry point for the console application.
//
# Include " Stdafx. h "
TypedefStructNode
{
IntVal;
StructNode*Next;
} Linknode,*Link;
Void CreateLink (Link * Head)
{
If ( * Head = Null)
* Head = New Linknode;
( * Head) -> Val = 38 ;
( * Head) -> Next = NULL;
Link P = * Head;
For ( Int I = 0 ; I < 9 ; I ++ )
{
Link newnode = New Node;
Newnode -> Val = I;
Newnode -> Next = P;
P = Newnode;
}
* Head = P;
}
Link reverse (link head)
{
If(Head=Null)
ReturnNULL;
Link p1=Head;
Link p2=Head->Next;
Link P = NULL;
While (P1 ! = Null)
{
P2 = P1 -> Next;
P1 -> Next = P;
P = P1;
P1 = P2;
}
// P1-> next = P; // Connect to the last Node
Return P;
}
Void Print (link head)
{
While (Head ! = Null)
{
Printf ( " % D " , Head -> Val );
Head = Head -> Next;
}
Printf ( " \ N " );
}
void destroy (link head)
{< br> link P = NULL;
while (head)
{< br> P = head -> next;
Delete head;
head = P;
}< BR >}
Int_ Tmain (IntArgc, _ tchar*Argv [])
{
Link head=NULL;
CreateLink (&Head );
Print (head );
Head=Reverse (head );
Print (head );
Destroy (head );
Return 0;
}