【面试题】反转链表的递归和非递归实现

  • 题目描述:

定义一个函数,输入链表的头结点,反转该链表并输出反转后链表的头结点。

链表定义如下:

struct Node
{
   DataType List;
   struct List* _pNext;
};

typedef struct List Node;
typedef Node *pNode;

反转是链表重复性的操作,可以用到递归,或者while()循环实现。

非递归法:

这里写图片描述

代码实现:

pNode ReceiveNodeList(pNode pHead)           
{
    pNode pTest = pHead;
    pNode pPre = NULL;

    if (pHead == NULL || pHead->_pNext == NULL)
        return pHead;

    while (pTest != NULL)
    {
        pNode pNextNode = pTest->_pNext;
        //简单的节点交换
        pTest->_pNext = pPre;
        pPre = pTest;
        pTest = pNextNode;
    }
    return pPre;
}
递归实现:

非递归方式是从前面1开始往后依次处理,而递归方式则恰恰相反,它先循环找到最后面指向的数,然后从后开始处理依次翻转整个链表。

这里写图片描述

代码实现:

pNode ReceiveNodeList_DG(pNode pHead)
{
    pNode pNewNode = NULL;
    if (pHead == NULL || pHead->_pNext == NULL)
        return pHead;

    pNewNode = ReceiveNodeList_DG(pHead->_pNext);

    pHead->_pNext->_pNext = pHead;   //翻转链表的指向
    pHead->_pNext = NULL;   //记得赋值NULL,防止链表错乱
    return pNewNode;        //新链表头永远指向的是原链表的链尾

}

猜你喜欢

转载自blog.csdn.net/m0_37925202/article/details/80668170
今日推荐