[leetcode-328]Odd Even Linked List(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)
            return head;
        ListNode oddHead = head,evenHead =head.next;
        ListNode prevOdd = oddHead,prevEven = evenHead;

        while(prevOdd.next != null && prevEven.next != null){
            prevOdd.next = prevEven.next;
            prevOdd = prevOdd.next;

            prevEven.next = prevOdd.next;
            prevEven = prevEven.next;
        }
        prevOdd.next = evenHead;

        return oddHead;
    }
}

你可能感兴趣的:(leetcode)