• LeetCode 328. Odd Even Linked List


    原题链接在这里:https://leetcode.com/problems/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.

    题解:

    要归类的是node的index而不是node的value. 双指针, 一个指向odd位置, 一个指向even位置.

    Time Complexity: O(n). Space: O(1).

    AC Java:

     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 || head.next.next == null){
    12             return head;
    13         }
    14         ListNode oddHead = head;
    15         ListNode evenHead = head.next;
    16         ListNode oddCur = oddHead;
    17         ListNode evenCur = evenHead;
    18         while(evenCur != null && evenCur.next != null){
    19             oddCur.next = evenCur.next;
    20             evenCur.next = evenCur.next.next;
    21             oddCur = oddCur.next;
    22             evenCur = evenCur.next;
    23         }
    24         oddCur.next = evenHead;
    25         return oddHead;
    26     }
    27 }
  • 相关阅读:
    产品中常用理论
    Mac下配置环境变量
    Maven仓库
    深入理解Spring中的各种注解
    JAVA中简单字符串分割
    WARN: HHH000277: Could not bind factory to JNDI
    dos命令窗口下下java命令提示找不到或无法加载主类
    数组实用类:Arrays
    数组
    线程创建方式
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5324744.html
Copyright © 2020-2023  润新知