LeetCode 328. Odd Even Linked List Java

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

Credits:
Special thanks to @aadarshjajodia for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

思路:

1 小于3个元素的,直接返回原有head

2 大于等于3个元素的

while循环{

2.1 建立odd 链表

2.2 建立even链表

}

odd链表尾部指针指向even链表的头部

3 返回head

代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
    public class Solution {
        public ListNode oddEvenList(ListNode head) {
        if(head == null || head.next == null) {//元素个数<3,直接返回头
            return head;                    
        }
    
        ListNode even = head.next, odd = head, evenHead = head.next;
    
        while(even != null && even.next != null) { //元素个数>=3&&循环能继续(even.next有值)
            odd.next = even.next; //odd元素指针指向even的下一个元素
            odd = odd.next;       //odd指针后移
            even.next = odd.next; //even元素指向odd的下一个元素
            even = even.next;     //even指针后移
        }
        odd.next = evenHead;//对接odd尾和even的头
        return head;
    }
}



你可能感兴趣的:(java,LeetCode,LinkedList)