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 }

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

  • 相关阅读:
    用Android Studio 开发Android应用
    以前写的一个下载小说的工具
    折半算法的C#实现方式-递归和非递归
    128. 最长连续序列
    一语点醒技术人:你不是 Google(转载)
    计算机专业导论与思维系统--哈工大
    安卓笔记 09_28
    安卓学习笔记
    安卓数据库08_29
    08_28学习笔记Kotlin
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5609577.html
Copyright © 2011-2022 走看看