zoukankan      html  css  js  c++  java
  • 面试题---两个有序单链表的合并

    #include <iostream>
    using namespace std;
    
    struct node{
        int value;
        struct node *next;
    };
    
    struct node *head1;
    struct node *head2;
    
    void insert(struct node * &head,int value)
    {
        if(head == NULL)
        {
            head = new struct node;
            head->value = value;
            head->next = NULL;
            return;
        }
    
        struct node *p = new struct node;
        p->value = value;
        p->next = NULL;
    
        struct node *q = head;
        while(q->next != NULL)
        {
            q = q->next;
        }
    
        q->next = p;
    
    }
    
    struct node *merge(struct node *head1,struct node *head2)
    {
    
        if(head1 == NULL)
            return head2;
        if(head2 == NULL)
            return head1;
        
        struct node *head = NULL;
        if(head1->value > head2->value)
        {
            head = head2;
            head->next = merge(head1,head2->next);
        }
        else
        {
            head = head1;
            head->next = merge(head1->next,head2);
        }
        return head;
    }
    
    void print(struct node *head)
    {
        struct node *p = head;
        while(p != NULL)
        {
            cout<<p->value<<"  ";
            p = p->next;
        }
    }
    
    int main()
    {
        head1 = NULL;
        head2 = NULL;
    
        insert(head1,1);
        if(head1 != NULL)
            cout<<"确实已经赋值了呀!
    ";
        insert(head1,3);
        insert(head1,5);
        insert(head1,9);
        insert(head1,11);
        insert(head1,16);
        insert(head1,18);
        insert(head2,6);
        insert(head2,10);
        insert(head2,12);
        insert(head2,13);
        insert(head2,15);
        insert(head2,18);
        cout<<"链表1:
    ";
        print(head1);
        cout<<endl;
        cout<<"链表2:
    ";
        print(head2);
        cout<<endl;
        cout<<"合并后为
    ";
        struct node *head = NULL;
        head = merge(head1,head2);
        if(head != NULL)
            print(head);
        cout<<endl;
        return 0;
    }
  • 相关阅读:
    四则运算试题生成,结对
    3 词频统计
    20190912-1 每周例行报告
    20190912-2 命令行
    每周例行报告
    作业要求 20190919-1 每周例行报告
    作业要求20190919-4 单元测试,结对
    作业要求 20190919-6 四则运算试题生成,结对
    作业要求20190919-5 代码规范,结对要求
    作业要求20190919-2 功能测试
  • 原文地址:https://www.cnblogs.com/qingergege/p/7782686.html
Copyright © 2011-2022 走看看