这段代码会将像 1-> 2 -> 3 -> 4 这样的链表转换为 1->3-2->4 (即左边奇数右边偶数),除了oddEvenSplitter
函数引起的问题。此代码将按值修改引用。在输入是参考的情况下如何重用代码?
public void oddEvenSplitter (Node head, Node current, Node temp) {
if (head == null) {
head = temp;
current = temp;
} else {
current.next = temp;
current = temp;
}
}
public void oddFirst( ) {
if (first == null) {
throw new NoSuchElementException();
}
Node temp = first;
Node oddhead = null;
Node odd = null;
Node evenhead = null;
Node even = null;
while (temp != null) {
if (temp.element % 2 == 0) {
oddEvenSplitter(evenhead, even, temp);
} else {
oddEvenSplitter(oddhead, odd, temp);
}
}
if (oddhead != null) {
odd.next = evenhead;
first = oddhead;
}
}