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 }

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

  • 相关阅读:
    安装 macbook 双系统( OS X 和 Ubuntu )
    微信小程序初探
    [Javascript] Promise
    [AS/400] 基本概念
    [AS/400] Control Language(CL) 基本概念
    [AS/400] Control Language
    [github] 创建个人网页
    [tools] sublime 使用记录
    [Java] TreeMap
    exe转msi
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5609577.html
Copyright © 2011-2022 走看看