劍指offer之面試題17合并兩個排序的鏈表

來源:互聯網
上載者:User

問題描述:

輸入兩個遞增的鏈表,合并這兩個鏈表並使新鏈表中的結點仍然是按照遞增排序的。

實現代碼如下:

#include <stdio.h>#include <stdlib.h>#include <stdbool.h>struct List{int date;struct List *next;};struct List* doMergeList(struct List *P1head,struct List *P2head){if(P1head==NULL)return P2head;else if(P2head==NULL)return P1head;struct List *mergeHead = NULL;if(P1head->date <P2head->date){mergeHead = P1head;mergeHead->next=doMergeList(P1head->next,P2head);}else {mergeHead=P2head;mergeHead->next=doMergeList(P1head,P2head->next);}return mergeHead;}int main(){struct List *P1head=(struct List *)malloc(sizeof(struct List));struct List *P2head=(struct List *)malloc(sizeof(struct List));P1head->date=0;P1head->next=NULL;P2head->date=1;P2head->next=NULL;int i;struct List *P1Temp=P1head,*P2Temp=P2head;for(i=1;i<4;i++){P1Temp->next=(struct List *)malloc(sizeof(struct List));P1Temp->next->date=i;P1Temp->next->next=NULL;P2Temp->next=(struct List *)malloc(sizeof(struct List));P2Temp->next->date=i*3;P2Temp->next->next=NULL;P1Temp=P1Temp->next;P2Temp=P2Temp->next;}P1Temp=P1head,P2Temp=P2head;printf("this is first list:\t");while(P1Temp!=NULL){printf("%d\t",P1Temp->date);P1Temp=P1Temp->next;}printf("\nthis is second list:\t");while(P2Temp!=NULL){printf("%d\t",P2Temp->date);P2Temp=P2Temp->next;}printf("\nthis is merge list:\t");struct List *Head = doMergeList(P1head,P2head);while(Head!=NULL){printf("%d\t",Head->date);Head=Head->next;}printf("\ndomerge done!\n");return 0;}

參考資料:
劍指offer

備忘:
轉載請註明出處:http://blog.csdn.net/wsyw126/article/details/51372134
作者:WSYW126

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.