题解 | 反转链表

反转链表

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




// 非递归
/*struct ListNode* ReverseList(struct ListNode* head ) {
    // write code here
    if (head->next == NULL || head == NULL) {
        return head;
    }
    struct ListNode* p = NULL; //前
    struct ListNode *c = head;  //当前
    struct ListNode *n = NULL;   //后

    while (c != NULL) {
         n=c->next;
         c->next=p;
         p=c;
         c=n;
    }
    return p;

}*/

//递归
struct ListNode* ReverseList(struct ListNode* head ) {
    if (head->next == NULL || head == NULL) {
        return head;
    }
    struct ListNode* n = ReverseList(head->next);
    head->next->next = head;
    head->next = NULL;
    return n;
}



全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

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