需注意:这里的奇数结点指的是结点在链表中的位置的奇偶性
我的解答:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
内容:LeetCode.328 奇偶结点分开
时间:2020/1/18
作者:hjw
*/
class Solution {
public ListNode oddEvenList(ListNode head) {
ListNode odd = new ListNode(0);//奇数结点的头节点
ListNode even = new ListNode(0);//偶数结点的头节点
ListNode p = head,tmp = null,pOdd = odd,pEven = even;
int i = 0;//结点下标
while(p!=null)
{
i++;
if(i%2!=0)//奇数结点放odd链表
{
tmp = p.next;
pOdd.next = p;
pOdd = pOdd.next;
pOdd.next = null;
p = tmp;
}
else//偶数结点放even链表
{
tmp = p.next;
pEven.next = p;
pEven = pEven.next;
pEven.next = null;
p = tmp;
}
}
pOdd.next = even.next;//偶数节点的首结点连接到奇数结点的末尾
return odd.next;
}
}
算法:
将奇节点放在一个链表里,偶链表放在另一个链表里。然后把偶链表接在奇链表的尾部。
官方题解:
public class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null) return null;
ListNode odd = head, even = head.next, evenHead = even;
while (even != null && even.next != null) {
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next;
}
odd.next = evenHead;
return head;
}
}