Skip to content

Latest commit

 

History

History
36 lines (33 loc) · 589 Bytes

File metadata and controls

36 lines (33 loc) · 589 Bytes
  • 递归解法
class Solution {
 public:
  ListNode* reverseList(ListNode* head) {
    if (!head || !head->next) {
      return head;
    }
    ListNode* t = reverseList(head->next);
    head->next->next = head;
    head->next = nullptr;
    return t;
  }
};
  • 非递归解法
class Solution {
 public:
  ListNode* reverseList(ListNode* head) {
    if (!head) return nullptr;
    ListNode* pre = nullptr;
    ListNode* cur = head;
    while (cur) {
      ListNode* t = cur->next;
      cur->next = pre;
      pre = cur;
      cur = t;
    }
    return pre;
  }
};