程序员面试宝典之数据结构基础---⑤单链表逆序的递归与非递归实现

#include <iostream>
#include <stdio.h>
using namespace std;

struct ListNode
{
    ListNode* p_Next;
    int p_Value;
};
ListNode* Reverse_List(ListNode* pHead)
{
    //非递归实现单链表逆序输出。
    ListNode* pHead_New = NULL;
    ListNode* pTemp = pHead;
    ListNode* pAfter = NULL;
    ListNode* pPre = NULL;
    //第一种写法:
    while(pHead!= NULL)
    {
        pAfter = pHead->p_Next;
        pHead->p_Next = pPre;
        pPre =  pHead;
        pHead = pAfter;
        //pAfter = pAfter->p_Next;//多此一举
    }
    pHead = pPre;
    return pHead;

    //第二种写法:
    /*
    while(pTemp != NULL)
    {
    	pAfter = pTemp->p_Next; //save the next Node

    	if(pAfter == NULL)
        	pHead_New = pTemp;
    	pTemp->p_Next = pPre;
   	 pPre = pTemp;
   	 pTemp = pAfter;
    }
    return pHead_New;
    */

}
ListNode* Reverse_List_recurrence(ListNode* pHead)
{
    //递归调用实现单链表逆序。
    //ListNode* new_head = pHead;
    if(pHead == NULL || pHead->p_Next == NULL) //空或者只有一个节点
        return pHead;
    else
    {
        ListNode* new_Head = Reverse_List_recurrence(pHead->p_Next);
        pHead->p_Next->p_Next = pHead;
        pHead->p_Next = NULL;
        return new_Head;
    }
}
int main()
{
    //Test case! //simple test

    ListNode a,b,c,d;
    a.p_Value = 1, a.p_Next = &b;
    b.p_Value = 2, b.p_Next = &c;
    c.p_Value = 3, c.p_Next = &d;
    d.p_Value = 4, d.p_Next = NULL;
    /*
    a->p_Value = 1, a->p_Next = b;
    b->p_Value = 2, b->p_Next = c;
    c->p_Value = 3, c->p_Next = d;
    d->p_Value = 4, d->p_Next = NULL;
    */
    ListNode* pHead = &a;
    printf("%d %d\n", pHead->p_Value,pHead->p_Next->p_Value);
    printf("%d %d %d %d \n",a.p_Value ,b.p_Value, c.p_Value, d.p_Value);

   ListNode* p = Reverse_List_recurrence(pHead);
   printf("%d %d\n", p->p_Value,p->p_Next->p_Value);
   printf("%d %d %d %d \n",a.p_Value ,b.p_Value, c.p_Value, d.p_Value);


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值