LeetCode-328~Odd Even Linked List

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 ...
给定一个链表,将所有奇数位置节点放在一起,后面放置偶数位置节点。

算法分析

方法一:

新建两个链表,一个放置奇数节点,一个放置偶数节点,最后将偶数链表头放到奇数链表尾节点之后。

Java代码
/**
 * 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) {
        ListNode current = head;//链表当前节点
        int i = 1;
        ListNode ji = new ListNode(0);//奇数链表头
        ListNode jiCurr = ji;//奇数链表尾
        ListNode ou = new ListNode(0);//偶数链表头
        ListNode ouCurr = ou;//偶数链表尾
        while(current != null) {
            if (i % 2 == 1) {
                jiCurr.next = new ListNode(current.val);
                jiCurr = jiCurr.next;
            } else {
                ouCurr.next = new ListNode(current.val);
                ouCurr = ouCurr.next;
            }
            i ++;
            current = current.next;
        }
        jiCurr.next = ou.next;
        return ji.next;
    }
}
方法二:

类似于方法一,不过此方法不用新建链表,而是在原来链表基础上。


LeetCode-328~Odd Even Linked List_第1张图片
方法二
Java代码
/**
 * 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) return head;
        ListNode odd = head, even = odd.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;
    }
}

参考

LeetCode
oschina

你可能感兴趣的:(LeetCode-328~Odd Even Linked List)