/**
 * 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

 

posted on 2017-06-09 08:48  Sempron2800+  阅读(121)  评论(0编辑  收藏  举报