题目看错了,我把所有的奇数放到了所有偶数的前面。
下面是代码对应的不是这个题目。
package myTest;
import java.util.Random;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import myTest.ListNode;
public class Solution {
public static ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode t = head;
ListNode flag = null; // flag 指向最后一个奇数
if(t.val%2 == 1 || t.val%2 == -1)
{
flag = t;
}
while( t.next != null ){
if ( t.next.val%2 == 1 || t.next.val%2 == -1)
{
if (flag == null)
{
flag = t.next;
t.next = flag.next;
flag.next = head;
head = flag;
}
else
{
if (flag.next == t.next) // 相邻奇数
break;
ListNode temp = flag;
ListNode temp2 = flag.next;
flag = t.next;
t.next = flag.next;
temp.next = flag;
flag.next = temp2;
}
}
else
t = t.next;
}
return head;
}
private static void outPut(ListNode head){
while( head != null )
{
System.out.print(head.val+", ");
head = head.next;
}
System.out.println();
}
public static void main(String args[])
{
ListNode head = null;
for(int i = 0;i < 10;i++){
Random random = new Random();
int pos = random.nextInt() % 100 > 0 ? random.nextInt() % 100 : -(random.nextInt() % 100);
ListNode t = new ListNode(pos);
t.next = null;
if( head != null){
t.next = head;
}
head = t;
}
outPut(head);
outPut(oddEvenList(head));
}
}
public static ListNode oddEvenList(ListNode head) {
if(head == null)
return head;
ListNode first = head;
ListNode second = head.next;
ListNode temp = second;
while(second != null && second.next != null)
{
first.next = second.next;
first = first.next;
second.next = first.next;
second = second.next;
}
first.next = temp;
return head;
}
写个链表都写的这么费劲呢