题目:
将链表中的所有元素为奇数的节点移到元素为偶数节点的前面,并使奇数之间顺序反转,偶数之间顺序反转。
示例:
交换前链表的顺序 交换后链表的顺序
4→5→7→1→6 ==> 1→7→5→6→4
1 ==> 1 (链表仅含一个元素)
2→1 ==> 1→2
==> (链表为空)
思路:定义奇数偶数分别的链表,
原链表 2—>3—>4—>5—>6:
结果:5—>3—>6—>4—>2
奇数链表:3—>5
偶数链表:2—>4—>6
偶数+奇数:2—>4—>6—>3—>5
反转链表5—>3—>6—>4—>2
package exam;
/*
* 链表保持顺序奇数在前偶数在后,并且反转链表
*/
public class Demo {
public static void main(String[] args) {
Node n1 = new Node(2);
Node n2 = new Node(3);
Node n3 = new Node(4);
Node n4 = new Node(5);
Node n5 = new Node(6);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
Node n = getOddEvenNode(n1);
System.out.println(n);
}
// 奇数偶数归类
public static Node getOddEvenNode(Node node) {
if (node == null || node.next == null)
return node;
Node oddHead = new Node(0);
Node odd = new Node(0);
oddHead.next = odd;
Node evenHead = new Node(0);
Node even = new Node(0);
evenHead.next = even;
int k = 0;
while (node != null) {
if (node.val % 2 == 0) {
even.next = node;
even = even.next;
} else {
odd.next = node;
odd = odd.next;
}
k++;
node = node.next;
}
even.next = oddHead.next.next;
node = evenHead.next.next;
return reverse(node, k);
}
// 反转链表 ,统计个数,定义头结点head,定义初始尾节点是node的第一个节点,后面的每个节点都插入到head和next中间,next不断的变化
public static Node reverse(Node node, int k) {
Node head = new Node(0);
// 中间节点,保存每次node下一个值,
Node interNode = null;
interNode = node.next;
node.next = null;
Node next = node;
head.next = node;
node = interNode;
int inter = 1;
while (node != null && inter != k) {
interNode = node.next;
node.next = null;
head.next = node;
node.next = next;
next = node;
node = interNode;
inter++;
}
return head.next;
}
}