328. Odd Even Linked List

来源:互联网 发布:淘宝估值 编辑:程序博客网 时间:2024/06/07 09:02

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 ...


奇数位的节点依次连在一起偶数位的节点依次连在一起跟在奇数位节点的后面

注意共有奇数个节点的处理,在将最后一个奇数节点处理之后不要忘记处理 最后一个偶数节点的下一位 置null



public class Solution {    public ListNode oddEvenList(ListNode head) {        if(head==null||head.next==null||head.next.next==null) return head;        ListNode odd=head;        ListNode even=head.next;        ListNode evenhead=head.next;        while(odd.next.next!=null&&even.next.next!=null){            odd.next=odd.next.next;            even.next=even.next.next;            odd=odd.next;            even=even.next;        }        if(odd.next.next!=null){            odd.next=odd.next.next;            odd=odd.next;            even.next=null;        }        odd.next=evenhead;        return head;    }}


0 0