struct ListNode |
2 | { |
3 | void* m_nKey; |
4 | ListNode* m_pNext; |
5 | }; |
常规实现:
01 | ListNode* ReverseIteratively(ListNode* pHead) |
02 | { |
03 | ListNode* pReversedHead = NULL; |
04 | ListNode* pNode = pHead; |
05 | ListNode* pPrev = NULL; |
06 | while(pNode != NULL) |
07 | { |
08 | // get the next node, and save it at pNext |
09 | ListNode* pNext = pNode->m_pNext; |
10 |
11 | // if the next node is null, the currect is the end of original |
12 | // list, and it's the head of the reversed list |
13 | if(pNext == NULL) |
14 | pReversedHead = pNode; |
15 |
16 | // reverse the linkage between nodes |
17 | pNode->m_pNext = pPrev; |
18 |
19 | // move forward on the the list |
20 | pPrev = pNode; |
21 | pNode = pNext; |
22 | } |
23 | } |
递归实现(不需要临时节点):
01 | ListNode* reverse_list( ListNode* head) //逆序 |
02 | { |
03 | ListNode* new_head=head; |
04 | if(head==NULL || head->next==NULL) |
05 | return head; |
06 | new_head = reverse_list(head->next); |
07 | head->next->next=head; |
08 | head->next=NULL; //防止链表成为一个环,这是最关键的。 |
09 | return new_head; |
10 | } |