Question: Enter the head node of a linked list to reverse the linked list. The linked list node is defined as follows:
Struct listnode
{
Void * m_nkey;
Listnode * m_pnext;
};
For general implementation, two temporary nodes are required:
Listnode * reverseiteratively (listnode * phead)
{
Listnode * preversedhead = NULL;
Listnode * pnode = phead;
Listnode * pprev = NULL;
While (pnode! = NULL)
{
// Get the next node, and save it at pnext
Listnode * pnext = pnode-> m_pnext;
// If the next node is null, The currect is the end of original
// List, and it's the head of the reversed list
If (pnext = NULL)
Preversedhead = pnode;
// Reverse the linkage between nodes
Pnode-> m_pnext = pprev;
// Move forward on the list
Pprev = pnode;
Pnode = pnext;
}
Recursive Implementation (no temporary node is required ):
Listnode * reverse_list (listnode * head) // reverse
{
Listnode * new_head = head;
If (Head = NULL | head-> next = NULL)
Return head;
New_head = reverse_list (Head-> next );
Head-> next = head;
Head-> next = NULL; // It is critical to prevent the linked list from becoming a ring.
Return new_head;
}
The above code has been tested.