In-place iterative and recursive C++ solution


  • 1
    W
    1. recursive:

      class Solution {

      public:

      ListNode *root;
      ListNode* reverse(ListNode *head) {
          if (head) return reverse(head->next)->next = head;
          else return root;
      }
      ListNode* reverseList(ListNode* head) {
          root = new ListNode(0);
          reverse(head)->next = NULL;
          return root->next;
      }
      

      };

    2. iterative:

      class Solution {

      public:

      ListNode* reverseList(ListNode* head) {
      
          if (!head) return head;
          ListNode *root = new ListNode(0);
          root->next = head;
          ListNode *pre = root;
          while (head) {
              ListNode *tmp = head;
              head = head->next;
              tmp->next = pre;
              pre = tmp;
          }
          (root->next)->next = NULL;
          return pre;
      }
      

      };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.