• Reorder List [LeetCode]


    Given a singly linked list LL0L1→…→Ln-1Ln,
    reorder it to: L0LnL1Ln-1L2Ln-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}.

    Solution: make sure the last element points to NULL in the new list;

     1     void reorderList(ListNode *head) {
     2         vector<ListNode * > nodes;
     3         ListNode * current = head;
     4         while(current != NULL) {
     5             nodes.push_back(current);
     6             current = current->next;
     7         }
     8         for(int i = 0; i < nodes.size() / 2; i ++){
     9             int next = nodes.size() - 1 - i;
    10             if(i < next){
    11                 ListNode * tmp = nodes[i]->next;
    12                 nodes[i]->next = nodes[next];
    13                 nodes[next]->next = tmp;
    14             }
    15         }
    16         if(nodes.size() > 0)
    17             nodes[nodes.size() / 2]->next = NULL;
    18     }
     1     void reorderList(ListNode *head) {
     2         vector<ListNode * > nodes;
     3         ListNode * current = head;
     4         while(current != NULL) {
     5             nodes.push_back(current);
     6             current = current->next;
     7         }
     8         for(int i = 0; i < nodes.size() / 2; i ++){
     9             if(i < nodes.size() - 1 - i){
    10                 nodes[i]->next = nodes[nodes.size() - 1 - i];
    11                 if(i + 1 < nodes.size() - 1 - i)
    12                     nodes[nodes.size() - 1 - i]->next = nodes[i + 1];
    13                 else
    14                     nodes[nodes.size() - 1 - i]->next = NULL;
    15             }
    16         }
    17         if(nodes.size() % 2 == 1)
    18             nodes[nodes.size() / 2]->next = NULL;
    19     }
  • 相关阅读:
    最近学习下,nohup和&的区别
    java 关键字
    iOS之事件穿透
    排序算法——快速排序
    分布式-选举算法
    分布式选举算法
    SolrCloud 分布式集群部署步骤
    linux 启动两个tomcat
    solr安装-tomcat+solrCloud构建稳健solr集群
    JAVA 中BIO,NIO,AIO的理解
  • 原文地址:https://www.cnblogs.com/guyufei/p/3415575.html
Copyright © 2020-2023  润新知