Recursive version and iterative version


  • 3
    X
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if (NULL == head || NULL == head->next) return head;
            ListNode * nextTail = head->next;
            ListNode * nextHead = reverseList(head->next);
            nextTail->next = head;
            head->next = NULL;
            return nextHead;
        }
    };
    
    
    
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if (NULL == head || NULL == head->next) return head;
            ListNode * cur = NULL, * pre = head;
            while (pre != NULL) {
                ListNode * nextNode = pre->next;
                pre->next = cur;
                cur = pre;
                pre = nextNode;
            }
            return cur;
        }
    };

  • 0
    D

    recursive solution by c:

    struct ListNode* reverseList(struct ListNode* head) {
            if(head==NULL || head->next==NULL)
                return head;
            else
                {
               struct    ListNode *next_node=head->next;
                head->next=NULL;
                struct  ListNode *n_head=reverseList(next_node);
                next_node->next=head;
                return n_head;
                
                
            }
            
        }

Log in to reply
 

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