您的位置:首页 > 其它

链表逆序

2012-10-22 17:24 162 查看
struct ListNode
2{
3void* m_nKey;
4ListNode* m_pNext;
5};
常规实现:

01ListNode* ReverseIteratively(ListNode* pHead)
02{
03

ListNode* pReversedHead = NULL;
04ListNode* pNode = pHead;
05ListNode* pPrev = NULL;
06while(pNode != NULL)
07{
08// get the next node, and save it at pNext
09ListNode* 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
13if(pNext == NULL)
14pReversedHead = pNode;
15
16// reverse the linkage between nodes
17pNode->m_pNext = pPrev;
18
19// move forward on the the list
20pPrev = pNode;
21pNode = pNext;
22}
23}
递归实现(不需要临时节点):

01ListNode* reverse_list( ListNode* head) //逆序
02{
03ListNode* new_head=head;
04if(head==NULL || head->next==NULL)
05return head;
06new_head = reverse_list(head->next);
07head->next->next=head;
08head->next=NULL; //防止链表成为一个环,这是最关键的。
09return new_head;
10}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: