328. Odd Even Linked List

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

You must solve the problem in O(1)extra space complexity and O(n) time complexity.


class Solution {

    public ListNode oddEvenList(ListNode head) {

        if(head == null || head.next == null) return head;

        ListNode odd = head;

        ListNode even = head.next;

        ListNode p1 = odd, p2 = even;

        while(p1.next != null && p2.next != null){

            p1.next = p1.next.next;

            p2.next = p2.next.next;

            p1 = p1.next;

            p2 = p2.next;

        }

        p1.next = even;


        return odd;

    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容