法一:python–3指针插入法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if head==None or head.next==None:
return head
front=head
psecond=front.next
obj=psecond.next
while obj:
psecond.next=obj.next
obj.next=front.next
front.next=obj
front=obj
psecond=psecond.next
if psecond:
obj=psecond.next
else:
break
return head
法二:C++奇偶链表合并法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (head==NULL || head->next==NULL) return head;
ListNode *odd=head, *even=head->next,*r=even;
while(even->next){
odd->next=even->next;
odd=odd->next;
even->next=odd->next;
if(even->next) even=even->next;
}
odd->next=r;
return head;
}
};