构建两个假头和两个指针,然后奇数位置节点挂在dummy后面,偶数节点位置挂在dummy2后面
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy1 = new ListNode(0, head);
ListNode dummy2 = new ListNode(0, null);
ListNode currrnt1 = head;
ListNode current2 = dummy2;
while(currrnt1.next != null || current2.next != null) {
if (current2.next == null) {
current2.next = currrnt1.next;
current2 = current2.next;
currrnt1.next = null;
} else {
currrnt1.next = current2.next;
current2.next = null;
currrnt1 = currrnt1.next;
}
}
currrnt1.next = dummy2.next;
return dummy1.next;
}
}