https://leetcode-cn.com/problems/odd-even-linked-list/
思路:一个链表存奇数节点,另外一个存偶数节点,再把他们连起来即可。注意哨兵的作用。
/**
* 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) {
ListNode odd(0),even(0);//哨兵
ListNode *head1=&odd,*head2=&even;
ListNode *cur=head;
bool flag=1;
while(cur){
if(flag)
head1->next=cur,head1=cur;
else
head2->next=cur,head2=cur;
cur=cur->next;
flag=!flag;
}
head1->next=even.next;
head2->next=nullptr;
return odd.next;
}
};