zoukankan      html  css  js  c++  java
  • leetcode328

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode OddEvenList(ListNode head) {
            if (head != null)
                {
                    ListNode odd = head, even = head.next, evenHead = even;
    
                    while (even != null && even.next != null)
                    {
                        odd.next = odd.next.next;
                        even.next = even.next.next;
                        odd = odd.next;
                        even = even.next;
                    }
                    odd.next = evenHead;
                }
                return head;
        }
    }

    https://leetcode.com/problems/odd-even-linked-list/#/description

    补充一个python的实现:

     1 class Solution:
     2     def oddEvenList(self, head: 'ListNode') -> 'ListNode':
     3         l = list()
     4         while head:
     5             l.append(head.val)
     6             head = head.next
     7 
     8         even = None
     9         odd = None
    10         temp = None
    11         if len(l) == 0:
    12             return None
    13         for i in range(len(l)-1,-1,-1):
    14             if i % 2 == 0:
    15                 curodd = ListNode(l[i])
    16                 if not temp:
    17                     temp = curodd
    18                 curodd.next = odd
    19                 odd = curodd
    20             else:
    21                 cureven = ListNode(l[i])
    22                 cureven.next = even
    23                 even = cureven
    24         temp.next = even
    25         return odd

    补充一个简化版本的,执行效率更高:

     1 class Solution:
     2     def oddEvenList(self, head: ListNode) -> ListNode:
     3         if head == None:
     4             return None
     5         odd,even,evenhead = head,head.next,head.next
     6         while even != None and even.next != None:
     7             odd.next = odd.next.next
     8             odd = odd.next
     9             even.next = even.next.next
    10             even = even.next
    11         odd.next = evenhead
    12         return head
  • 相关阅读:
    Subway POJ
    Invitation Cards POJ
    Cow Contest POJ
    MPI Maelstrom POJ
    Wormholes POJ
    Currency Exchange POJ
    Codeforces Round #608 (Div. 2) D Portals
    AcWing 1052. 设计密码
    AcWing 1058. 股票买卖 V 状态机模型dp
    AcWing 1057. 股票买卖 IV 状态机模型dp
  • 原文地址:https://www.cnblogs.com/asenyang/p/6970241.html
Copyright © 2011-2022 走看看