反转链表
链接
https://leetcode-cn.com/problems/reverse-linked-list/
代码
/**
* 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) {
ListNode* pre = NULL;
ListNode* next = head;
ListNode* curr = head;
while(next != NULL){
curr = next;
next = curr->next;
curr->next = pre;
pre = curr;
}
return curr;
}
};
总结
记录前后节点
穿针引线
空间复杂度O(1)