方法一:
ListNode *FindMid(ListNode* head){
ListNode *p=head,*q=head;
while(q->next!=NULL&&q->next->next!=NULL){
p=p->next;
q=q->next->next;
}
return p;
}
方法二:
ListNode* FindMid(ListNode* head){
ListNode *pre=NULL,*p=head,*q=head;
while(q!=NULL&&q->next!=NULL){//q每次都比p多走一步,這樣當q到終點時,p正好到中間,用pre記錄p前一個節點
pre=p;
q=q->next->next;
p=p->next;
}
if(pre!=NULL){
pre->next=NULL;//從p點斷開,分爲以head和p爲頭節點的兩個鏈表
}
return p;//返回以p爲頭節點的兩個鏈表
}
方法三:
ListNode* FindMid(ListNode* head){
ListNode *p=head,*q=head->next;
while(q!=NULL&&q->next!=NULL){
p=p->next;
q=q->next->next;
}
return p;
}