第一种
创建两个链,将奇偶分开插入链中,最后奇偶链连接起来。
class Solution {
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null) return head;
//记录当前遍历节点位子
ListNode l1h = head; //奇数链 头节点
ListNode l1 = l1h ;
ListNode l2h =head.next; //偶数链头节点
ListNode l2 = l2h;
ListNode node = head.next.next;
int n = 1;
while(node != null) {
if(n % 2 != 0) {
l1.next = node;
l1 = l1.next;
}else {
l2.next = node;
l2 = l2.next;
}
node = node.next;
n++;
}
l2.next = null;
l1.next = l2h;
return l1h ;
}
}
第二种
直接在原链表的基础设置奇偶节点,分别为l1,l2然后上插入。
奇节点需要连接的节点为偶节点的下一个节点 表示为: l1. next = l2.next。
更新 奇节点位子 l1 = l1.next 。
偶节点需要连接的节点为奇节点的下一个节点 表示为: l2.next = l1.next。
循环后,将l1与 l2的头节点拼接
class Solution {
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode l1 = head; //奇数链
ListNode l2 = head.next; //偶数链
ListNode l2h = l2; //偶数链头节点
while(l2 != null && l2.next != null) {
l1.next = l2.next;
l1 = l1.next;
l2.next = l1.next;
l2 = l2.next;
}
l1.next = l2h;
return head ;
}
}