力扣24 两两交换链表中的节点()-其他
力扣24 两两交换链表中的节点()
两两交换链表中的节点:
先把一个链表分为两个链表,再把两个链表组成一个链表。
注意最后可能有一个链表有剩余,但此时另一个链表的指针已经到了NULL,要再遍历一遍/提前记录(感觉有点麻烦)。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode* new1=new ListNode(),*e1=new1;
ListNode* new2=new ListNode(),*e2=new2;
int n=0;
ListNode* p=head;
while(p){
if(n%2==0){
e1->next=p;
e1=p;
p=p->next;
}
else{
e2->next=p;
e2=p;
p=p->next;
}
n++;
}
e1->next=NULL;
e2->next=NULL;
p=new2->next; //2的遍历指针
ListNode* q=new1->next; //1的遍历指针
while(1){
if(p==NULL||q==NULL)
break;
ListNode* next2=p->next; //2的后节点
ListNode* next1=q->next; //1的后节点
p->next=q;
q->next=next2;
q=next1;
p=next2;
}
p=new1;
if(q!=NULL)
{
while(p->next)
p=p->next;
p->next=q;
q->next=NULL;
}
return new2->next;
}
};
————————
两两交换链表中的节点:
先把一个链表分为两个链表,再把两个链表组成一个链表。
注意最后可能有一个链表有剩余,但此时另一个链表的指针已经到了NULL,要再遍历一遍/提前记录(感觉有点麻烦)。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode* new1=new ListNode(),*e1=new1;
ListNode* new2=new ListNode(),*e2=new2;
int n=0;
ListNode* p=head;
while(p){
if(n%2==0){
e1->next=p;
e1=p;
p=p->next;
}
else{
e2->next=p;
e2=p;
p=p->next;
}
n++;
}
e1->next=NULL;
e2->next=NULL;
p=new2->next; //2的遍历指针
ListNode* q=new1->next; //1的遍历指针
while(1){
if(p==NULL||q==NULL)
break;
ListNode* next2=p->next; //2的后节点
ListNode* next1=q->next; //1的后节点
p->next=q;
q->next=next2;
q=next1;
p=next2;
}
p=new1;
if(q!=NULL)
{
while(p->next)
p=p->next;
p->next=q;
q->next=NULL;
}
return new2->next;
}
};