一開始老是想着交換節點的值,但是這特麼是鏈表又不是數組,直接把奇數位的節點拿出來拼成一條鏈,偶數位也拼成一條鏈,然後將後者拼接到前者末尾,搞定。。。。。。。。。。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null){
return head;
}
ListNode p1 = head;
ListNode p2 = head.next;
ListNode temp1 = p1;
ListNode temp2 = p2;
int count = 1;
ListNode temp3 = p2.next;
ListNode temp4 = null;
while (temp3 != null){
temp4 = temp3.next;
if (count % 2 != 0){
temp1.next = temp3;
temp1 = temp1.next;
}else {
temp2.next = temp3;
temp2 = temp2.next;
}
temp3.next = null;
temp3 = temp4;
count++;
}
temp2.next = null;
temp1.next = p2;
return p1;
}
}