• 面试题---两个有序单链表的合并


    #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;
    }
  • 相关阅读:
    《秒杀系统架构分析与实战 》
    《豆瓣的基础架构》
    转--《亿级用户下的新浪微博平台架构 》
    转-《蚂蚁金服11.11:支付宝和蚂蚁花呗的技术架构及实践 》
    hdu2029
    hdu2027
    hdu2026(water~~)
    PHP电影小爬虫(2)
    今天来做一个PHP电影小爬虫。
    PHP Simple HTML DOM解析器
  • 原文地址:https://www.cnblogs.com/qingergege/p/7782686.html
Copyright © 2020-2023  润新知