zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Python基础知识篇
    Django框架
    Django REST Framework框架
    NoSQL
    MySQL恩恩怨怨
    Python奇技淫巧
    一文搞定Flask
    数据结构与算法(Python)
    学习数据分析
    项目杂项
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5324744.html
Copyright © 2011-2022 走看看