206. 反转链表(c++)

阅读 68

2022-02-03

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == nullptr){
            return nullptr;
        }
        ListNode* res = nullptr;
        while(head){
            ListNode* temp = head->next;//先储存下一个节点
            head->next = res;//把下一个节点指向res的nullptr指针
            res = head;//res指针往head移动
            head = temp;//head往后移
        }
        return res;


    }
};

精彩评论(0)

0 0 举报