zoukankan      html  css  js  c++  java
  • 328. Odd Even Linked List java solutions

    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.

    Subscribe to see which companies asked this question

     
     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 || head.next == null) return head;
    12         ListNode oddcur = head;
    13         ListNode evencur = head.next;
    14         ListNode oddhead = new ListNode(-1);
    15         ListNode evenhead = new ListNode(-1);
    16         oddhead.next = oddcur;
    17         evenhead.next = evencur;
    18         
    19         head = head.next;
    20         int count = 1;
    21         while(head.next != null){
    22             if(count%2 == 1){
    23                 oddcur.next = head.next;
    24                 oddcur = oddcur.next;
    25             }else{
    26                 evencur.next = head.next;
    27                 evencur = evencur.next;
    28             }
    29             count++;
    30             head = head.next;
    31         }
    32         evenhead = evenhead.next;
    33         evencur.next = null;//这里偶链需要特殊处理,防止链循环。否则内存超出
    34         oddcur.next = evenhead;
    35         return oddhead.next;
    36     }
    37 }

    奇链串在一起,偶链串在一起,再拼起来 就是答案了。

  • 相关阅读:
    C/C++ 读文件
    算法和数据结构 图表示
    protobuf
    C/C++ jsoncpp
    C/C++ C++11作用域枚举
    腾讯云云函数快速入门实践
    Serverless 与 Flask 框架结合进行 Blog 开发
    从企业微信机器人到小爱同学,用 Serverless 实现生活智能化!
    基于 Serverless 与 Websocket 的聊天工具实现
    云函数 SCF 与对象存储实现 WordCount 算法
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5609577.html
Copyright © 2011-2022 走看看