zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    |,&,<<,>>运算符
    Unity 异步加载场景
    string字母排序,
    冒泡算法
    Direct3D 12 编程---(1)
    点云密度粗估计
    git工具使用
    opencv---灰度图像与彩色图像遍历
    求平面两直线的交点,两直线段的交点
    结构体重载运算符
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5745994.html
Copyright © 2011-2022 走看看