解法一:迭代法
class Solution {
public:ListNode* reverseList(ListNode* head) {if(!head)return NULL;auto p1 = head, p2 = p1->next;//定义两个相邻指针while(p2) {auto p3 = p2->next; //p3存储p2的后继节点p2->next = p1; //后面节点指针指向前面的节点p1 = p2;//双指针统一向后偏移p2 = p3;} head->next=NULL;return p1;}
};
解法二:递归法
class Solution {
public:ListNode* reverseList(ListNode* head) {if (!head || !head->next) return head;ListNode *tail = reverseList(head->next);head->next->next = head;head->next = nullptr;return tail;}
};