【算法】链表:206.反转链表(easy)

时间:2024-10-02 15:32: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 head; //快慢双指针 //直接一个一个结点的反转 ListNode* cur = NULL, *NEXT = head; while (NEXT != NULL) { ListNode* tmp = NEXT->next;//tmp临时指针,存放未被反转的链表,防止丢失 NEXT->next = cur; cur = NEXT; NEXT = tmp; } return cur; } };