题解 | #反转链表#

反转链表

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 
 * @return ListNode类
 */
 /* 法一:三指针反向*/
 #include <stdio.h>
#include <stdlib.h>
#if 0  
struct ListNode* ReverseList(struct ListNode* head ) {
    // write code here
    if(head ==NULL) return head;

    struct ListNode *pre =NULL;
    struct ListNode *nxt =NULL;

    while (head != NULL) 
    {
        nxt = head->next;
        head->next = pre;
        pre = head;
        head = nxt;
    }

    return pre;
}
#endif


/* 法二:虚拟头 + 头插法 */
#if 1
struct ListNode* ReverseList(struct ListNode* head ) {
    // write code here
    if(head ==NULL) return head;

    struct ListNode * virtual_head = malloc(sizeof(struct ListNode));//创建虚拟节点
    virtual_head->next = head;
    virtual_head->val = -1;

    struct ListNode * cur =head->next;
    struct ListNode * tail=head ; 
    //一个节点情况已排除,后续至少为两个实体节点。
    //假设只有2个实体节点,只要保证nxt最多等于一次next就好了

    while (cur!=NULL) 
    {
        /* 3+1步:倒着处理单链表, 逐步交叉:该点next等于上一个 */
        tail->next = cur->next;
        cur->next = virtual_head->next;
        virtual_head->next = cur;
        //处理节点指针移动到下一个
        cur = tail->next;
    }
    return virtual_head->next;
}
#endif

全部评论

相关推荐

专业嗎喽:个人信息名字太大,合到电话邮箱那一栏就行,有党员写过党,剩下其他全删,站空太大了 把实习经历丰富,放最前面,然后是个人评价,技能之类的,然后是学校信息。项目经历最后面,可以就选一个自己擅长的。 现在是学校不是92就扣分的,没必要放前面。 然后现在看重实习经历>竞赛经历(校园经历)>课程项目经历
点赞 评论 收藏
分享
11-13 12:02
门头沟学院 Java
我要娶个什么名:好骂,好骂 别学计算机就行了
点赞 评论 收藏
分享
12-14 22:54
武汉大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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