题解 | #反转链表#(指针数组法,迭代法,递归法)

反转链表

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

建立一个指针数组,先遍历一遍链表,在遍历时将指向每一个节点的指针存入指针数组中,并找到最后一个节点记作wei。最后,以wei为头节点在反向输出这个数组为p->next赋值,以创建一个反向的链表。

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param pHead ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead )
{
    if(pHead==NULL)
        return pHead;
    struct ListNode* cout[1000];
    int i=0;
    struct ListNode* p=pHead;
    struct ListNode* wei=NULL;
    while(p->next!=NULL)
    {
        cout[i++]=p;
        p=p->next;
    }
    wei=p;
    i=i-1;
    while(i>=0)
    {
        p->next=cout[i--];
        p=p->next;
    }
    p->next=NULL;
    return wei;
}

利用三个指针进行迭代。

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param pHead ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead )
{
    struct ListNode *cur=pHead;
    struct ListNode *newhead=NULL;
    struct ListNode *next;
    cur=pHead;//cur指向现在正在处理的节点
    newhead=NULL;//newhead指向正在处理的节点的上一个节点
    while(cur!=NULL)
    {
        next=cur->next;//next指向cur的下一个节点
        cur->next=newhead;
        newhead=cur;
        cur=next;
    }
    return newhead;
}

递归法

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param pHead ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead )
{
    if(pHead==NULL||pHead->next==NULL)
    return pHead;
    struct ListNode * newhead=ReverseList(pHead->next);
    pHead->next->next=pHead;
    pHead->next=NULL;
    return newhead;
}

执行到struct ListNode *newhead=ReverseList(pHead->next);

时,程序被编译器记录进入栈的位置,并且开始进栈(递归中的递),程序从头开始,每一次到struct ListNode *newhead=ReverseList(phead->next);

时,重复之前的操作,直到最深处——

if(pHead==NULL||pHead->next==NULL)

return pHead;

符合if语句条件,pHhead被返回出来了具体的值——5,于是程序开始出栈(递归中的归),返回到上一层此时pHead=4。由于程序记录了进栈的位置,出栈时就从进栈的下一句开始执行——执行pHead->next->next=pHead;

pHead->next=NULL;

return newhead;

这三句。newhead在执行这三句时没有被操作,所以值不变。每重复一边这三句话pHead的值就减少1。

全部评论

相关推荐

这算盘打的
程序员小白条:都这样的,都是潜规则,你自己说可以实习一年就行了,实习可以随便跑路的
点赞 评论 收藏
分享
07-10 11:08
门头沟学院 Java
投递京东等公司9个岗位
点赞 评论 收藏
分享
码农索隆:力扣的题目还挺贴近现实
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 12:20
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务