鑑於鏈接列表,我試圖將它分區,使偶數節點出現在奇數節點之前。我的方法是創建兩個不同的鏈表(偶數和奇數)來存儲偶數和奇數。然而,當我想要添加到偶數或奇數鏈表時,我遇到了一個問題(我在下面的代碼中評論了我認爲給我帶來問題的部分)。謝謝!分離鏈接列表中的偶數和奇數節點
public class SeperateOddEven {
static Node head;
static int count;
public static class Node {
int data;
Node next;
private Node(int data) {
this.data = data;
next = null;
count++;
}
}
public void seperate() {
Node even = null;
Node odd = null;
Node temp;
// go through each linked-list and place node in new list depending on whether they are even or odd
while(head != null) {
// if even, place in even linked-list
if(head.data % 2 == 0) {
temp = new Node(head.data);
even = temp; // Problem here
even = even.next; // and here
} else { // if head.data % 2 != 0
temp = new Node(head.data);
odd = temp;
odd = odd.next;
}
head = head.next;
}
toString(even);
//toString(odd);
}
public void toString(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
SeperateOddEven s = new SeperateOddEven();
head = new Node(8);
head.next = new Node(12);
head.next.next = new Node(10);
head.next.next.next = new Node(5);
head.next.next.next.next = new Node(4);
head.next.next.next.next.next = new Node(1);
head.next.next.next.next.next.next = new Node(6);
System.out.println("original list: ");
s.toString(head);
s.seperate();
}
}
請參考[這裏](http://stackoverflow.com/questions/11150609/how-to -arrange-all-even-numbers-in-odd-numbers-in-a-linked-list/36505517#36505517) – craftsmannadeem