题解 | #反转链表#

反转链表

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;
}
全部评论

相关推荐

2 收藏 评论
分享
牛客网
牛客企业服务