链表逆序

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}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值