Accept answer in c++ using stack


  • 0
    S

    there are three steps to finish it:
    1、store node in stack
    2、delete last node in list
    3、insert last node after current node

    class Solution {
    public:
        void reorderList(ListNode* head) {
            if(head==NULL || head->next==NULL || head->next->next==NULL) return;
            ListNode *cur=NULL, *last=NULL;
            stack<ListNode*> s;
            cur = head;
            while(cur!=NULL){
                s.push(cur);
                cur = cur->next;
            }
            cur = head;
            while(cur!=NULL && cur->next!=NULL){
                last = s.top();
                s.pop();
                s.top()->next = NULL;
                last->next = cur->next;
                cur->next = last;
                cur = cur->next->next;
            }
        }
    };
    

Log in to reply
 

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