面試題 將兩個公升序排列的鍊錶合併成乙個公升序鍊錶

2021-08-21 04:39:41 字數 1033 閱讀 9993

將兩個公升序排列的鍊錶合併成乙個有序鍊錶

例如:  head1->2->3->5->6->7->9->11

head2->2->4->5->7->9

合併之後結果為:head->2->2->3->4->5->5->6->7->7->9->9->11

**如下:

/*設head1和head2是兩個非空單向鍊錶,資料值有重複且公升序排序

將head1和head2合併成乙個公升序鏈

*/#include#include//定義結構體單元

typedef struct nodeelemsn;

//逆向建立單向鍊錶(頭插法)

elemsn *precreatlink(int a,int n)

return head;

} elemsn* combine(elemsn *head1,elemsn *head2)

else

p->next=null;

if(!head)

head=tail=p;

else

}if(head1)

p=head1;

else

p=head2;

tail->next=p;

return head; }

//列印鍊錶所有結點的值

void printlink(elemsn* head)

int main(void)

; int b[5]=;

head1=precreatlink(a,7); //建立鍊錶head1

head2=precreatlink(b,5); //建立鍊錶head2

head=combine(head1,head2); //將兩個有序鍊錶合併成乙個有序鍊錶

printlink(head); //輸出鍊錶

}

執行結果如下:

將兩個公升序排列的鍊錶合併後公升序排序列印

include include include define len sizeof struct student struct student int n 全域性變數n 用記錄鍊錶的結點數.struct student creat void 建立鍊錶的函式原型宣告.void print struct...

面試題 合併兩個有序的鍊錶

題目 輸入兩個遞增有序的鍊錶,合併這兩個鍊錶後,使新鍊錶中的結點 也是遞增有序的。遞迴方式實現兩個有序鍊錶的合併 struct listnode listnode merge listnode phead1,listnode phead2 else if phead2 null listnode m...

面試題25 合併兩個排序鍊錶

題目 輸入兩個遞增排序的鍊錶,合併這兩個鍊錶並使新鍊錶中的結點仍然是按照遞增排序的。include include list.h using namespace std struct listnode listnode mergetwolists listnode phead1,listnode p...