1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution {10 public:11 ListNode* cut(ListNode *head){12 int count=0;13 ListNode *temp=head;14 while(temp!=NULL)15 {16 ++count;17 temp=temp->next;18 }19 ListNode *lastHead=head;20 for(int i=0;i<(count+1)/2;i++)21 {22 lastHead=lastHead->next;23 }24 ListNode *p,*q;25 if(lastHead!=NULL&&lastHead->next!=NULL&&lastHead->next->next!=NULL)26 {27 p=lastHead;28 q=lastHead->next;29 lastHead->next=NULL;30 ListNode *tempcut=q->next;31 while(tempcut!=NULL)32 { 33 q->next=p;34 p=q;35 q=tempcut;36 tempcut=tempcut->next;37 }38 q->next=p;39 ListNode *last=q;40 return last;41 }42 else if(lastHead->next==NULL)43 {44 lastHead->next=NULL;//应该把尾节点的next赋为空45 return lastHead;46 }47 else if(lastHead->next->next==NULL)48 {49 p=lastHead;50 lastHead=lastHead->next;51 lastHead->next=p;52 p->next=NULL;//应该把尾节点的next赋为空53 return lastHead;54 }55 }56 void reorderList(ListNode *head) {57 if(head==NULL||head->next==NULL||head->next->next==NULL)58 return;59 else60 {61 ListNode *last=cut(head);62 ListNode *p,*q;63 p=head->next;64 q=last->next;65 while(p!=NULL&&q!=NULL)66 {67 head->next=last;68 last->next=p;69 head=p;70 last=q;71 p=p->next;72 q=q->next;73 }74 head->next=last;75 last->next=p;76 p->next=NULL;//应该把尾节点的next赋为空77 }78 }79 };
由于没给尾节点赋空值导致各种错误。