328. Odd Even Linked List

来源:互联网 发布:购物车订单数据库设计 编辑:程序博客网 时间:2024/06/06 00:52
Discuss Pick One

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



思路:两个listnode分别指向奇数节点和偶数节点。最后得到两个链表,将偶数节点组成的链表放到奇数节点组成的链表后面。
注意:什么时候退出循环?需要考虑的是由于第一个数是奇数节点,那么奇数节点一定等于偶数节点的个数或者多一个,后一种情况偶数链表最后会指向null,如果此时调用even.next就会抛出异常。所以要用短路与进行判断,一旦odd.next=null(说明even=null)就不必执行even.next. 如果是前一种情况,那么even.next会先为空。
class Solution {    public ListNode oddEvenList(ListNode head) {        if((head==null)||(head.next==null))            return head;        else{            ListNode odd = head, evenhead;            ListNode even = head.next;            evenhead = even;            // while(even.next != null){            while(odd.next!=null && even.next != null){                odd.next = even.next;                odd = odd.next;                even.next = odd.next;                even = even.next;            }            odd.next = evenhead;            return head;        }            }}


原创粉丝点击