题解 | #反转链表#

反转链表

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

class Solution {
public:
    ListNode* ReverseList(ListNode* head) {

        // 1.如果头节点为空,或者只有1个节点,则无需排序
        if ( head == nullptr || head->next == nullptr ) return head;  
        // 2.新建标记节点
        ListNode * p = head->next, * q = head->next;
        // 3.断开链表,一分为二
        head->next = nullptr; 

        while ( q != nullptr )
        {
            p = q;           // 需要修改的位置先跟上标志位 
            q = q->next;     // 标志位后移
            p->next = head;  // 插入到最前面
            head = p;        // 更新最新头的位置
        }
        return head;         // 返回头
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务