使用双指针法,注意一下更新左右指针的顺序就好了。这里还要注意一下终止条件,画个图就行了。leetcode里面头节点就是第一个存储数据的节点,没有虚拟头节点
class Solution {
public:ListNode* reverseList(ListNode* head) {ListNode* left;ListNode* right;ListNode* temp;left = NULL;right = head;while(right){ temp = right->next;right->next = left;left = right;right = temp;}return left;}
};
递归:
class Solution {
public:ListNode* MyreversList(ListNode* left, ListNode* right){if(right == NULL) return left;ListNode* temp;temp = right->next;right->next = left;return MyreversList(right, temp);}ListNode* reverseList(ListNode* head) {return MyreversList(NULL, head);}
};