Use stack to implement reorder list (Accepted)


  • -1
    A

    class Solution {
    public:
    void reorderList(ListNode *head) {
    if (!head || !head->next || !head->next->next) return;

        stack<ListNode *>st;
        ListNode *cur = head;
        int size = 0;
        while (cur)
        {
            size ++;
            st.push(cur);
            cur = cur->next;
        }
        cur = head;
        int count = 0;
        while (count < size/2)
        {
            ListNode *tmp = cur->next;
            cur->next = st.top();
            cur->next->next = tmp;
            cur = tmp;
            st.pop();
            count ++;
        }
        cur->next = NULL;
    }
    

    };


  • 0
    L

    You do not solve this problem in-place..


Log in to reply
 

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