当然大部分链表题都可以先把节点值出来进行处理后再放进去,但是这就失去了这些题的意义,
这个题主要考查的链表的逆置和合并。
首先说一下逆置,逆置,主要需要三个指针,一个指向p1,指向p2,一个指向p3,首先需要p3保存p2的next值,
然后才可以改变p2的指针,让其指向p1,然后把p2赋值p1,把p3赋值给p2,以此类推即可完成逆置,
至于合并,有些类似,让p1指向第一个链表,p2指向第二个链表,p3保存p1的next值,p2插入p1的next。
class Solution {
public:
void reorderList(ListNode *head) {
if(head==NULL||head->next==NULL)
return ;
ListNode *slow=head,*fast=head->next,*tem;
while(fast!=NULL&&fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
for(tem=slow->next,slow=slow->next=NULL;tem&&tem->next;slow=tem,tem=fast){
fast=tem->next;
tem->next=slow;
}
tem->next=slow;
for(fast=head;tem&&fast;tem=tem->next,fast=fast->next->next=slow){
slow=fast->next;
fast->next=tem;
}
}
};