合并链表 【微软面试100题 第二十四题】

题目要求:

  合并链表。已知链表h1和链表h2都是递增链表,要求合并后也是递增链表。

  参考链接:http://blog.csdn.net/v_july_v/article/details/6870251

  原链接代码while(h1 != NULL && h2 != NULL)应该修改为while(h1 != NULL || h2 != NULL)

代码实现:

#include <iostream>



using namespace std;



typedef struct ListNode

{

    struct ListNode *next;

    int data;

}ListNode;



ListNode *Merge(ListNode *h1, ListNode *h2);

void InitList(ListNode **head1,ListNode **head2);

void PrintList(ListNode *h);



int main(void)

{

    ListNode *h1 = NULL,*h2 = NULL;

    ListNode *mergeList = NULL;

    

    InitList(&h1,&h2);

    cout << "h1:";

    PrintList(h1);

    cout << endl << "h2:";

    PrintList(h2);

    cout << endl;

    mergeList = Merge(h1,h2);

    cout << "mergeList:";

    PrintList(mergeList);



    return 0;

}

void PrintList(ListNode *h)

{

    while(h!=NULL)

    {

        cout << h->data << " ";

        h = h->next;

    }

    cout << endl;

}

ListNode *Merge(ListNode *h1, ListNode *h2) 

{

    if(h1 == NULL) return h2;

    if(h2 == NULL) return h1;

    ListNode *head;

    if(h1->data>h2->data) 

    {

        head = h2; 

        h2=h2->next;

    }

    else 

    {

        head = h1;

        h1=h1->next;

    }



    ListNode *current = head;

    while(h1 != NULL || h2 != NULL) 

    {

        if(h1 == NULL || (h2!=NULL && h1->data>h2->data))

        {

            current->next = h2;

            h2=h2->next; 

            current = current->next;

        }

        else

        {

            current->next = h1;

            h1=h1->next; 

            current = current->next;

        }

    }

    current->next = NULL;

    return head;

}

//head1:1-->5-->9-->NULL

//head2:2-->4-->10-->NULL

void InitList(ListNode **head1,ListNode **head2)

{

    ListNode *tmp = new ListNode;

    tmp->data = 1;

    *head1 = tmp;



    tmp = new ListNode;

    tmp->data = 5;

    (*head1)->next = tmp;



    ListNode *tmp1 = new ListNode;

    tmp1->data = 9;

    tmp1->next = NULL;

    tmp->next = tmp1;



    tmp = new ListNode;

    tmp->data = 2;

    *head2 = tmp;



    tmp = new ListNode;

    tmp->data = 4;

    (*head2)->next = tmp;



    tmp1 = new ListNode;

    tmp1->data = 10;

    tmp1->next = NULL;

    tmp->next = tmp1;

}
View Code

你可能感兴趣的:(面试)