这道题,思考过,目前想的解决方案是使用双链表解决。
下面贴自己的Java代码实现:
/** * 题目描述: * 输入一个整数数组,实现一个函数来调整该数组中数字的顺序, * 使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分, * 并保证奇数和奇数,偶数和偶数之间的相对位置不变。 * * @author ihaokun * @date 2019/7/14 21:00 */ public class ReOrderArray { public static void main(String[] args) { reOrderArray(new int[]{1, 2, 3, 4, 5}); } /** * 初步审题,感觉数组操作add、delete不方便 * 把它变成链表再进行排序操作,最后转化为数组 * * @param array 整数数组 */ public static void reOrderArray(int[] array) { // 奇数节点、偶数节点,先设置为null DoubleLinkedList oddNumNode = new DoubleLinkedList(); DoubleLinkedList evenNumNode = new DoubleLinkedList(); for (int num : array) { DoubleLinkedList node; if (num % 2 == 1) { node = new DoubleLinkedList(num, oddNumNode,null); oddNumNode.next = node; oddNumNode = oddNumNode.next; } else if (num % 2 == 0){ node = new DoubleLinkedList(num, evenNumNode, null); evenNumNode.next = node; evenNumNode = evenNumNode.next; } } while (evenNumNode.prev != null){ evenNumNode = evenNumNode.prev; } // 除去偶数首位的0 evenNumNode = evenNumNode.next; // 先奇后偶 oddNumNode.next = evenNumNode; while (oddNumNode.prev != null){ oddNumNode = oddNumNode.prev; } // 除去奇数首位的0 oddNumNode = oddNumNode.next; // 排序后结果: while (oddNumNode != null){ System.out.println(oddNumNode.value); oddNumNode = oddNumNode.next; } } private static class DoubleLinkedList { private int value; private DoubleLinkedList prev; private DoubleLinkedList next; private DoubleLinkedList(){ } private DoubleLinkedList(int value, DoubleLinkedList prev, DoubleLinkedList next){ this.value = value; this.prev = prev; this.next = next; } } }