Reverse Linked List II in c++


  • 0
    S

    ...

    class Solution {
    ListNode* reverse(ListNode* head)
    {
    ListNode* curr = head;
    ListNode* next = NULL;
    ListNode* prev = NULL;
    while(curr != NULL)
    {
    next = curr->next;
    curr->next = prev;
    prev = curr;
    curr = next;
    }
    return prev;
    }
    public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
    if(head == NULL)
    return NULL;
    ListNode* revs=NULL, *revs_prev=NULL, *revend=NULL, revend_next=NULL;
    int i = 1;
    ListNode
    temp = head;
    while(i<=n && temp != NULL)
    {
    if(i<m)
    {
    revs_prev = temp;
    }
    if(i==m)
    {
    revs = temp;
    }
    if(i==n)
    {
    revend = temp;
    revend_next = temp->next;
    }
    temp = temp->next;
    i++;
    }
    revend->next = NULL;
    revend = reverse(revs);
    if(revs_prev)
    revs_prev->next = revend;
    else
    head = revend;
    revs->next = revend_next;
    return head;
    }
    };

    ...


Log in to reply
 

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