題目:已知兩個鏈表head1 和head2 各自有序,請把它們合並成一個鏈表依然有序。(保留所有結點,即便大小相同)
循環實現:
1.重新申請一個頭結點,使用指針p指向他,每新加一個結點,就將指針p后移一位,即指針p永遠指向新鏈表的尾結點
2.由於所用鏈表第一個結點不賦值,因此指針需要開始從頭結點的下一個結點開始判斷,如果兩個指針都為非空,將data域較小的指針連在新鏈表的末尾
3.當兩個指針有一個到達鏈表的結尾時,將沒有到達末尾的鏈表連接到新鏈表之后
遞歸實現:
1.函數返回條件是有一個鏈表結束,則返回另一個鏈表
2.取兩個指針data域較小的作為新的頭結點,遞歸調用
實現代碼如下:
#include<iostream> using namespace std; struct listnode { int data; listnode *next; }; //尾插法創建鏈表 listnode *init() { listnode *head=new listnode; head->next=NULL; listnode *p=head; cout<<"please input a number(按-1結束)"<<endl; int data; cin>>data; while(data!=-1) { listnode *temp=(listnode *)malloc(sizeof(listnode)); temp->data=data; temp->next=p->next; p->next=temp; p=temp; cout<<"please input a number(按-1結束)"<<endl; cin>>data; } return head; } //打印鏈表 void print(listnode *head) { listnode *p=head->next; while(p) { cout<<p->data<<" "; p=p->next; } cout<<endl; } //將兩個有序鏈表合並(循環實現) listnode *hebing(listnode *head1,listnode *head2) { listnode *head=new listnode; head->next=NULL; //聲明兩個指針分別指向兩個鏈表的數據開始部分 listnode *p1=head1->next; listnode *p2=head2->next; //聲明一個指針來指向新鏈表的最后一個結點,開始時指向head listnode *last=head; while(p1!=NULL && p2!=NULL) { //p1結點的數據小:將last指向p1結點,last和p1分別后移 if(p1->data<p2->data) { last->next=p1; p1=p1->next; last=last->next; } //p2結點數據小:將last指向p2結點,last和p2分別后移 else { last->next=p2; p2=p2->next; last=last->next; } } //當有一個鏈表結束時候,將last指向還未結束的鏈表 if(p1==NULL) last->next=p2; else if(p2==NULL) last->next=p1; return head; } //將兩個有序鏈表合並(遞歸實現) listnode *hebing2(listnode *head1,listnode *head2) { //循環結束條件:當一個鏈表到達結尾 if(head1==NULL) return head2; if(head2==NULL) return head1; listnode *head=NULL; //選擇兩個頭結點中較小的作為頭結點 if(head1->data>head2->data) { head=head2; head->next=hebing2(head1,head2->next); } else { head=head1; head->next=hebing2(head1->next,head2); } return head; } //因為輸出時候第一個結點時空的,需要填加一個空的頭結點 listnode *diguihebing(listnode *head1,listnode *head2) { listnode *head=new listnode; head->next=hebing2(head1->next,head2->next); return head; }
測試代碼以及運行結果:
int main() { listnode *head1=init(); print(head1); listnode *head2=init(); print(head2); //listnode *head=hebing(head1,head2);//測試循環代碼 //print(head); listnode *head=diguihebing(head1,head2);//測試遞歸代碼 print(head); delete head,head1,head2; return 0; }