给定一个链表,把所有奇数节点放到偶数节点之前,奇节点和偶节点的相对位置不变。
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null || head.next.next == null)
return head;
ListNode listOdd = new ListNode(0);
ListNode listEven = new ListNode(0);
ListNode currOdd = head;
ListNode currEven = head.next;
ListNode tailOdd = listOdd;
ListNode tailEven = listEven;
while(true){
tailOdd.next = currOdd;
tailEven.next = currEven;
tailOdd = currOdd;
tailEven = currEven;
if(currOdd.next.next != null && currEven.next.next != null){
currOdd = currOdd.next.next;
currEven = currEven.next.next;
}
else if(currOdd.next.next != null){ //若链表要奇数个节点,需加上
currOdd = currOdd.next.next;
tailOdd.next = currOdd;
tailOdd = currOdd;
break;
}
else
break;
}
tailOdd.next = listEven.next;
tailEven.next = null;
return listOdd.next;
}