• LeetCode-Odd Even Linked List


    Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

    You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

    Example:
    Given 1->2->3->4->5->NULL,
    return 1->3->5->2->4->NULL.

    Note:
    The relative order inside both the even and odd groups should remain as it was in the input.
    The first node is considered odd, the second node even and so on ...

    Credits:
    Special thanks to @DjangoUnchained for adding this problem and creating all test cases.

    Solution:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode oddEvenList(ListNode head) {
    11         if (head==null) return head;
    12         
    13         ListNode preHead = new ListNode(-1);
    14         preHead.next = head;
    15         
    16         ListNode oddEnd = head;
    17         ListNode evenEnd = head.next;
    18         
    19         while (evenEnd!=null && evenEnd.next!=null){
    20             ListNode target = evenEnd.next;
    21             evenEnd.next = evenEnd.next.next;
    22             target.next = oddEnd.next;
    23             oddEnd.next = target;
    24             oddEnd = oddEnd.next;
    25             evenEnd = evenEnd.next;
    26         }
    27         
    28         return preHead.next;
    29     }
    30 }
  • 相关阅读:
    Kibana 地标图可视化
    Filebeat 日志收集
    ELK + Redis 日志收集 & HAProxy
    RAID 磁盘阵列
    Logstash 日志收集(补)
    ELK Stack 介绍 & Logstash 日志收集
    ElasticSearch 集群 & 数据备份 & 优化
    ElasticSearch 交互使用
    网络通信体系
    面向对象思想
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5745994.html
Copyright © 2020-2023  润新知