参考来源:http://vichargrave.com/reversing-a-singly-linked-list/
Reverse the List
Now the function you have been waiting for. The trick to this algorithm is you need 3 node_tpointers to accomplish the reversal.
- next - Tracks the pointer to the next item in the list.
- head - Initially contains the original head of the list but will then be set to the pointer to the next item in the list until the NULL pointer is encountered.
- cursor - Initially is set to NULL but then tracks the new head of the list. At the end of the list, head equals NULL and the value of cursor is returned to the caller.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
node_t* reverseList(node_t* head)
{
node_t* cursor = NULL;
node_t* next;
while
(head)
{
next = head->m_next;
head->m_next = cursor;
cursor = head;
head = next;
}
return
cursor;
|