leetcode 328. Parity list java

topic:

Given a single list, all the nodes of the odd and even rows, respectively, with the node. Note that, here node odd and even parity node refers to a node number, rather than the value of the parity nodes.

Try using in-place algorithm is complete. Space complexity of your algorithm should be O (1), time complexity should total number of nodes is O (nodes), nodes.

Example 1:

Input: 1-> 2-> 3-> 4- > 5-> NULL
Output: 1-> 3-> 5-> 2- > 4-> NULL
Example 2:

Input: 2-> 1-> 3-> 5- > 6-> 4-> 7-> NULL
Output: 2-> 3-> 6-> 7- > 1-> 5-> 4-> NULL
Description:

The relative order of the odd and even number of nodes of the nodes should be kept.
The list of the first node considered odd node, the second node as an even number of nodes, and so on.

Problem solving:

/**
 * 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) return null;
        ListNode odd = head, even = head.next, evenHead = even;
        while (even != null && even.next != null) {
            odd.next = even.next;
            odd = odd.next;
            even.next = odd.next;
            even = even.next;
        }
        odd.next = evenHead;
        return head;
    }
}

https://leetcode-cn.com/problems/odd-even-linked-list/solution/qi-ou-lian-biao-by-leetcode/

Guess you like

Origin www.cnblogs.com/yanhowever/p/11806612.html