题解 | #反转链表#

反转链表

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

双指针迭代法

 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */

/**
 * 
 * @param pHead ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead ) {
    // write code here
    //双指针迭代法
    struct ListNode* p=NULL;
    struct ListNode* q=NULL;
    //q为下一个要指向的链表节点
    //p为记录原链表的下一个节点,转换方向后避免丢失
    while(pHead!=NULL)
    {
        p=pHead->next;
        pHead->next=q;
        q=pHead;
        pHead=p;
    }
    return q;
}

头插法

 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
/**
 * 
 * @param pHead ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead ) {
    // write code here
    //头插法
    struct ListNode* H=malloc(sizeof(struct ListNode));
    H->next=NULL;
    struct ListNode* cur=pHead;
    struct ListNode* q=NULL;
    while(cur!=NULL)
    {
        q=cur;
        cur=cur->next;
        q->next=H->next;
        H->next=q;
    }
    return H->next;
}
全部评论

相关推荐

04-25 19:29
已编辑
宁波大学 运营
被普调的六边形战士很高大:你我美牛孩
点赞 评论 收藏
分享
不想投了,不想面了,不想找了感觉自己像个小丑
用微笑面对困难:不是你去大学生就业平台看看啊,boss很多就是冲kpi的
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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