/**
* 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) return nullptr;
ListNode* cur = head;
ListNode* pre = nullptr;
ListNode* next = new ListNode(); //next指针用来存储当前要操作的节点的下一个节点
while(cur){
next = cur -> next;
cur -> next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
<Talk is cheap, show me the code 35> LeetCode.206 反转链表
于 2024-07-12 15:50:09 首次发布