本题用了四个变量,作用分别是n1,n2寻找奇数下标和偶数下标;h1,h2分别是奇数的头结点和偶数头结点,最后将n1的next指向h2,将两数相连即可。
struct ListNode* oddEvenList(struct ListNode* head ) {
// write code
if(head==NULL || head->next==NULL || head->next->next==NULL)
{
return head;
}
struct ListNode* n1,*h1,*n2,*h2;
n1=h1=head;
n2=h2=head->next;
while(n1&&n1->next)
{
n1->next=n2->next;
if(n2->next==NULL)
break;
n1=n2->next;
n2->next=n1->next;
n2=n1->next;
}
n1->next=h2;
return h1;
}
struct ListNode* oddEvenList(struct ListNode* head ) {
// write code
if(head==NULL || head->next==NULL || head->next->next==NULL)
{
return head;
}
struct ListNode* n1,*h1,*n2,*h2;
n1=h1=head;
n2=h2=head->next;
while(n1&&n1->next)
{
n1->next=n2->next;
if(n2->next==NULL)
break;
n1=n2->next;
n2->next=n1->next;
n2=n1->next;
}
n1->next=h2;
return h1;
}