zoukankan      html  css  js  c++  java
  • [LeetCode] Reorder List

    Given a singly linked list LL0→L1→…→Ln-1→Ln,
    reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

    You must do this in-place without altering the nodes' values.

    For example,
    Given {1,2,3,4}, reorder it to {1,4,2,3}.

    Hide Tags
     Linked List
     

    分析:用stack保存link List,然后从后向前弹出,

    cur < total/2 时完成,最后把最后一个节点的next设置成NULL

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
        public:
            void reorderList(ListNode* head)
            {   
                if(head == NULL)
                    return ;
    
                ListNode* pFront = head;
                stack<ListNode*> st; 
                int totalNum = 0;
                int curNum = 0;
    
                while(pFront)
                {   
                    st.push(pFront);
                    pFront= pFront->next;
                    totalNum++;
                }   
    
                pFront = head;
                ListNode* pRear =  NULL;
    
                ListNode* tmp = NULL;
                while(curNum < totalNum/2)
                {   
                    pRear = st.top();
                    st.pop();
    
                    tmp = pFront->next;
                    pFront->next = pRear;
                    pRear->next = tmp;
                    pFront= tmp;
                    curNum ++; 
                }   
    
                //mark the end
                pFront->next = NULL;
    
            }
    };
  • 相关阅读:
    adb命令
    linux常用命令(2)
    Cisco路由器配置基本命令
    linux常用命令
    跨站脚本攻击xss
    选择合适的索引列顺序
    索引的选择性
    mysql索引类型(按存储结构划分)
    mysql数据类型优化
    vim基本命令总结
  • 原文地址:https://www.cnblogs.com/diegodu/p/4597791.html
Copyright © 2011-2022 走看看